python - 使用 Python 和 BeautifulSoup 从 Yahoo Finance 抓取股票价格
问题描述
我正在尝试使用 Python 和 BeautifulSoup 从 Yahoo Finance 获取股票价格。但是,我无法获取具有特定“data-reactid”属性的标签(参见屏幕截图)。请帮我。
Code:
def getCurrentPrice(self, stockSymbol):
#stockSymbol is : MSFT for Microsoft
url = "https://finance.yahoo.com/quote/{}".format(stockSymbol)
source = requests.get(url).text
soup = BeautifulSoup(source, 'lxml')
currentPrice = soup.find('span',attrs={"data-reactid": "52"})
print("{} : {}".format(stockSymbol, currentPrice))
Output:
MSFT : None
#None because the span tag is not being found.
解决方案
该属性data-reactid
本质上是动态的,因此您无法真正找到使用它的 dom 元素。尝试这个:
def getCurrentPrice(self, stockSymbol):
#stockSymbol is : MSFT for Microsoft
url = "https://finance.yahoo.com/quote/{}".format(stockSymbol)
source = requests.get(url).text
soup = BeautifulSoup(source, 'lxml')
currentPrice = soup.find('span',attrs={"class": "Trsdu(0.3s)"})
print("{} : {}".format(stockSymbol, currentPrice.get_text()))
推荐阅读
- python - 如何添加一个功能来监控使用 selenium 的链接点击?
- c++ - 使用向量的向量的 N 维矩阵类
- java - 如何在 Java 中安全地使用不可变类中的集合?
- flutter - 颤振 StreamBuilder 和 AnimatedWidget
- flutter - Flutter:在过滤 json 数据时获取“状态”实例
- javascript - 获取popup的路径url,保存在当前vue组件的变量中
- powershell - Powershell在添加注册表时以任何方式隐藏是和否弹出窗口
- python - 如何在 seaborn 图中显示交叉点标签?
- swift - 如何产生负楠?
- r - 如何在 R 中将 R 与 4 X 3 和 3 X 5 向量进行元素加法或乘法