python - Python Yahoo Finance - 数据抓取
问题描述
我是编程新手,我只是想获得“目标价格:来自 yahoo Finance 的价值我尝试了 beautifulsoup、xpath ......但在以下示例中从未成功提取数据 (241.21 $)
示例:https ://finance.yahoo.com/quote/MSFT/analysis?p=MSFT
import requests
from bs4 import BeautifulSoup as bs
ticker = 'MSFT'
url ='https://finance.yahoo.com/quote/'+Symbol
page = requests.get(url)
soup = bs(page.text, "html.parser")
for row in table:
col = row.find_all('span')
for c in col:
print(c.text)
打印所有跨度时,它不显示...
解决方案
我开发了以下示例来抓取您感兴趣的数据。这些数据特别难以获取,因为只有在页面向下滚动足够多时才由 javascript 填充它。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get('https://finance.yahoo.com/quote/MSFT/analysis?p=MSFT')
# Scroll down to the container of the data. The Analyst Price Targets div.
# The needed data is not filled in until scrolled down
driver.execute_script("""document.querySelector('div#Aside div[data-reactid="48"]').scrollIntoView();""")
# Get the span that contains the data
elem = driver.find_element_by_xpath("//div[@data-test='analyst-avg-tg']//span[2]")
print(elem.text)
推荐阅读
- tensorflow - 使用估计器进行多 gpu 训练
- java - ExecutorService 多线程
- c# - 尽管有管理员权限,但无法创建/写入注册表子项的值 C#
- python - 在 Google Cloud Talent Solution (python) 中创建公司时如何使用默认租户?
- youtube - 如何通过 api 将人员添加到我的品牌帐户?
- here-api - 为什么在后台线程调用 OnGestureListenerAdapter 的 onTapEvent 方法?
- r - 使用 Rscript 和 CMD 启动的闪亮应用程序在一段时间后不可用
- sql-server - 如何在现有变更数据捕获 (CDC) 表中添加更多列而不丢失任何数据
- sql-server - 当数据量很大时,索引查找操作是否比索引扫描更昂贵?
- python - 在 Databricks 中,如何在笔记本中创建具有动态变量的 SQL 函数