python - 使用 Beautiful Soup 从 Yahoo Finance 刮取标准偏差
问题描述
我正在尝试使用 BeautifulSoup 和 Python 2.7 从雅虎财务网页上的风险统计表中抓取一些数字: https ://finance.yahoo.com/quote/SHSAX/risk
到目前为止,我已经使用https://codebeautify.org查看了 html :
#!/usr/bin/python
from bs4 import BeautifulSoup, Comment
import urllib
riskURL = "https://finance.yahoo.com/quote/SHSAX/risk"
page = urllib.urlopen(riskURL)
content = page.read().decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
我的麻烦实际上是使用soup.find 获取数字。例如,标准差:
# std should be 13.44
stdevValue = float(soup.find("span",{"data-reactid":"124","class":"W(39%) Fl(start)"}).text)
# std of category should be 0.18
stdevCat = float(soup.find("span",{"data-reactid":"125","class":"W(57%) Mend(5px) Fl(end)"}).text)
这两个对soup.find 的调用都没有返回。我错过了什么?
解决方案
从我在网上阅读的内容来看,“data-reactid”是 react 框架用来引用组件的自定义属性(您可以在此处阅读更多内容,html 中的 data-reactid 属性是什么?),经过几次尝试,我注意到每个重新加载页面的data-reactid属性不同,像随机生成的一样。
我认为您应该尝试找到另一种方法来实现这一目标。
也许您可以尝试找到特定元素,例如“标准偏差”行,然后向下循环以收集数据。
std_span = next(x for x in soup.find_all('span') if x.text == "Standard Deviation")
parent_div = std_span.parent
for sibling in parent_div.next_siblings:
for child in sibling.children:
# do something
print(child.text)
希望能帮助到你。
推荐阅读
- json - 哪些APP或软件可以将IFC还原为JSON
- javascript - 在我的 theme.js.liquid 文件中使用产品的 variant.inventory_policy
- javascript - 如何在正则表达式匹配之前提取一行?
- python - 如何并行执行python subTests?
- javascript - 仅返回对象数组中的一些键
- sql-server - SSIS 指向旧连接
- sql - 如何在熊猫数据框中使用 python 进行时间连续性检查
- c# - 在 SQL 大容量复制期间检查数据库中是否存在数据的任何方法
- python - 如何从多个数据框中添加多个列,同时在 Python 中保持标识列不变?
- webauthn - FIDO2 与 U2F/CTAP1 的兼容性