使用Python和Beautiful Soup从文本中删除数字

2024-10-04 07:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个范围内(下面的代码)分离一个数字。我使用类在页面上查找我的信息,因为页面没有我要收集的特定信息的id,所以它提供了整行HTML代码。我希望能够将此实例中的数字与其他信息分开。我已经这样做的标题,并认为我可以使用类似的方法来这样做的价格

当我打印标题时,我得到了:普利司通公司(BRDCY)

当我打印价格时,我得到:<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="35">18.58</span>

如何提取18.58,使其成为唯一设置为price的字符串/int

from bs4 import BeautifulSoup

URL = 'https://finance.yahoo.com/quote/BRDCY?p=BRDCY&.tsrc=fin-srch'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find(id="Lead-3-QuoteHeader-Proxy").get_text()
price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")


#price = price[price.find(">"), price.find("<")]
title = title[0:title.find(")")+1]

print(price)
print(title)

Tags: 代码信息id标题title价格数字页面
1条回答
网友
1楼 · 发布于 2024-10-04 07:37:43

使用get_text()函数,就像您在标题中使用的一样

  price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

相关问题 更多 >