【问题标题】:Getting 'live' Yahoo Finance Data in Python使用 Python 获取“实时”雅虎财经数据
【发布时间】:2017-10-12 20:09:01
【问题描述】:

我一直在使用 urllib2 和直截了当的文本函数来读取彭博社的货币价格,以读取存储价格的 hmtl 部分。可能不会因效率而赢得任何奖励,但它已经适合我的目的。这是从页面被抓取的代码中提取的。

    #grab the html source as a big string

    response = urllib2.urlopen('https://www.bloomberg.com/quote/CHFGBP:CUR')

    page = response.read()

    #locate the html where price is stored

    pricestart = page.find('meta itemprop="price" content=')+len('meta itemprop="price" content=')

    #plus twenty characters

    price = page[pricestart:pricestart+20] 

    #find the data between double quotes in that substring

    pricesplit = price.split('"')

    #the 1st element of the output array is the price, cast it as a float

    priceAsFloat = float(pricesplit[1])

    #and save it to the current prices dictionary

    pricesCurr[keys] = priceAsFloat

我想为 Yahoo Finance 做同样的事情,因为它的更新频率更高,给人一种“实时”价格的感觉(我知道它们会延迟 15 分钟)。

但是,我在bloomberg html 上工作的方法不适用于雅虎源

查看这个网址,例如https://uk.finance.yahoo.com/quote/CHFJPY=X?p=GBPJPY=X

检查 urllib2.urlopen 返回的 html - 当前价格不在要抓取的文本中。或者至少我找不到它!

任何人都可以就如何抓取 yahoo Finance html 提供任何建议吗?

【问题讨论】:

  • Yahoo 不鼓励网络抓取财务数据 (stackoverflow.com/questions/38355075/…),而是更喜欢您转到 developer.yahoo.com,在那里您可以使用 API 及其 YQL(雅虎查询语言)虽然这不能回答您的问题回复:刮,这可能是获得所需结果的替代方法。
  • 这很有趣!大约一年前,我改用抓取Bloomberg,因为我通过API 和YQL 获取黄金现货价格的另一个脚本停止工作,并且我读到一个加载线程说API 已经停止。
  • 我应该自己检查一下 - 似乎它仍在运行。 developer.yahoo.com/yql/console/…

标签: python web-scraping yahoo-finance


【解决方案1】:

我也一直在处理雅虎财务数据。您正在寻找的价值就在那里,但它被埋没了。以下是我用来抓取雅虎财经的代码摘录:

from bs4 import BeautifulSoup
import urllib3 as url
import certifi as cert


def get_stock_price(name):
    http = url.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=cert.where())
    html_doc = http.request('GET', 'https://finance.yahoo.com/quote/' + name + '?p=' + name)
    soup = BeautifulSoup(html_doc.data, 'html.parser')
    return soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

其中name 是股票的简写名称(例如“tsla”)。为了找到要抓取的适当值,我手动向下钻取了 html,直到找到突出显示我正在搜索的值的部分。上面的代码适用于您提供的网站。

【讨论】:

  • 我今天注意到财务 API 已关闭(返回错误 999 请求被拒绝)所以我想我会尝试您的方法作为备份。您的代码运行良好,但数字似乎不会像实时雅虎页面那样对更改做出反应。任何想法为什么?例如,我正在查看英镑/美元的关系finance.yahoo.com/quote/GBPUSD=X,而美汤的回报率始终为 1.31,而雅虎网页则在 1.3122、1.3121 等之间跳跃。有什么想法吗?
  • 对于其他阅读者...答案是通过浏览器加载页面以便呈现...我使用硒
猜你喜欢
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多