如何使用BeautifulSoup提取带有data-reactid的span内容?

问题描述 投票:0回答:1

我想提取 Market Cap这个 雅虎金融网站。

enter image description here

enter image description here

我用

from bs4 import BeautifulSoup
import requests
url='https://finance.yahoo.com/quote/TXG?p=TXG&.tsrc=fin-srch'
wb_data=requests.get(url)
soup=BeautifulSoup(wb_data.text,'lxml')
cap = soup.find("span", class_ = "Trsdu(0.3s) ").get_text()
print(cap)

但我得到了 80.81 (即 "上一交易日"),而不是 "上一交易日"。8.01B. 这是因为 "前收盘价 "共享同一个类。所以我尝试通过使用 data-reactid. 如何实现这个目标?

我得到了答案,但它是如此的奇怪,它是。attrs = {"data-reactid": "57"} 而不是 139!

python beautifulsoup
1个回答
1
投票

find 函数将任何未知的关键字参数视为属性过滤器,因此要找到一个其 id 属性是 foo,你会写。

soup.find(id = "foo")

你不能用 data-class 直接作为关键字参数,因为连字符使它在 Python 中成为一个非法的标识符。但BeautifulSoup 覆盖了你:

cap = soup.find("span", class_ = "Trsdu(0.3s) ", attrs = {"data-reactid": "85"})

请注意,依赖React IDs可能非常脆,所以最好还是依赖周围的元素,比如那个 "市值 "标签。


1
投票

你可以尝试使用一个名为 yahooquery. 您可以通过以下方式获得该数据(以及该摘要选项卡上的大多数其他数据)。summary_detail 上的财产 Ticker 类。

from yahooquery import Ticker

tgx = Ticker('tgx')

data = tgx.summary_detail

# Market Cap
data['tgx']['marketCap']
8009946112

0
投票

试试这个。

from bs4 import BeautifulSoup
import requests
url='https://finance.yahoo.com/quote/TXG?p=TXG&.tsrc=fin-srch'
wb_data=requests.get(url)
soup=BeautifulSoup(wb_data.text,'lxml')
cap = soup.find("span", class_ = "Trsdu(0.3s) ").get('data-reactid')
print(cap)
© www.soinside.com 2019 - 2024. All rights reserved.