首页 > 解决方案 > 使用 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 的调用都没有返回。我错过了什么?

标签: pythonweb-scrapingbeautifulsoup

解决方案


从我在网上阅读的内容来看,“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)

希望能帮助到你。


推荐阅读