【问题标题】:How to retrieve live price from yahoo_finance stock?如何从 yahoo_finance 股票中检索实时价格?
【发布时间】:2017-12-10 15:09:23
【问题描述】:

我正在构建一个应用程序,我想从 yahoo-finance 检索最新报价。我正在尝试使用 BeautifulSoup 抓取路径,但是当我打印时得到的只是一个空列表。有什么建议吗?

示例 HTML:

<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="35"><!-- react-text: 36 -->169.37<!-- /react-text --></span>

我的代码:

 import requests
 from bs4 import BeautifulSoup
 a = requests.get('https://finance.yahoo.com/quote/AAPL/history?p=AAPL')
 soup = BeautifulSoup(a.content, 'lxml')
 search = soup.find_all('span', {'class':'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) 
 D(ib)'})
 print(search)

【问题讨论】:

  • 页面的内容很可能是由 ajax 引入的——你无法对其进行 scape。如果幸运的话,他们提供了 APOI,因此您无需抓取任何内容 - 只需使用 API。
  • @PatrickArtner 你知道我是否可以取消实时股票价格吗?也许来自另一个来源?谢谢
  • 你应该使用this library

标签: python web-scraping beautifulsoup yahoo-finance


【解决方案1】:

您可以将 selenium 与 BeautifulSoup 结合使用来获得您想要的内容。如下所示:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://finance.yahoo.com/quote/AAPL/history?p=AAPL')
soup = BeautifulSoup(driver.page_source,"lxml")
item = soup.find(id="quote-market-notice").find_parent().find("span").text
print(item)
driver.quit()

输出:

169.37

【讨论】:

  • 我目前正在使用 Visual Studio,虽然我已经安装了 bs4,但我遇到了错误。你知道为什么会这样吗?
  • 当谈到任何关于安装东西的建议时,我头晕目眩。你可以通过谷歌找到任何关于如何让bs4 工作的解决方案。顺便说一句,上面的代码值得一试。谢谢。
  • 它工作得几乎完美。我只是有一个问题。当我运行代码时,会弹出一个 Chrome 网页,其中包含我在上面代码中提供的 url。我怎么能阻止这个?我只是想得到号码。谢谢
  • 在这种情况下,您需要选择headless chrome driverphantomjs 或类似的驱动程序。但是,在处理点击事件或无限滚动网页时,这些无头驱动程序存在一些问题。
  • from selenium.webdriver.chrome.options import Options opts = Options() opts.set_headless() driver = webdriver.Chrome(options=opts);您可以使用此方法在不弹出的情况下抓取数据
【解决方案2】:

找到了一个python api:

https://pypi.python.org/pypi/yahoo-finance

>>> from yahoo_finance import Share   
>>> yahoo = Share('YHOO')  
>>> print yahoo.get_open()  
'36.60'  
>>> print yahoo.get_price()  
'36.84'  
>>> print yahoo.get_trade_datetime()  
'2014-02-05 20:50:00 UTC+0000'  

猜测一下,这会更容易使用并且更少损坏

【讨论】:

  • 好吧,它不起作用。我得到一个 YQLqueryError!它对你有用吗?
【解决方案3】:

您可以使用 yahoo_fin 包(请参阅http://theautomatic.net/yahoo_fin-documentation/)。这里有几个例子:

# load the stock_info module from yahoo_fin
from yahoo_fin import stock_info as si

# get Apple's live quote price
si.get_live_price("AAPL")

# or Amazon's
si.get_live_price("AMZN")

只需将“AAPL”或“AMZN”替换为您需要的任何代码即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2020-11-28
    • 2022-08-10
    • 2020-08-09
    • 2015-06-20
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多