Skip to main content
 首页 » 编程设计

python之使用python从HTML页面获取数据

2025年05月04日14fff_TT

我想使用 python 和 beautiful soup 从下面的标签中获取值 100

<span style="font-size:90%"><b>100</b> <cite style="color:#cc0000"><b>-0.10</b> (0.52%)</cite></span> 

下面的代码给出了以下输出

100 -0.10 (0.52%) 

如何只提取值 100?

代码:

from urllib.request import Request, urlopen 
import bs4  
import re 
 
url =  'url.com' 
req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) 
page = urlopen(req).read() 
soup = bs4.BeautifulSoup(page, 'html.parser') 
data = soup.find('span',style=re.compile('font-size:90%')) 
value = data.text 

请您参考如下方法:

可以得到soup.contents的第一个元素:

from bs4 import BeautifulSoup as soup 
d = soup(page, 'html.parser').find('span', {'style':'font-size:90%'}).contents[0].text 

输出:

'100'