【问题标题】:Web scraping JS content with Python (Yahoo Finance)使用 Python 抓取 JS 内容(雅虎财经)
【发布时间】:2017-03-27 07:43:50
【问题描述】:

我目前正在努力处理雅虎财经的这个页面:https://sg.finance.yahoo.com/quote/1B0.SI/history?period1=1426780800&period2=1489939200&interval=div%7Csplit&filter=split&frequency=1mo

我需要获取股票分割的日期和比率,但我进入了一个 json 文件,其中我没有看到任何这些信息!

我正在使用这里提到的脚本How to understand this raw HTML of Yahoo! Finance when retrieving data using Python?

from bs4 import BeautifulSoup
from pprint import pprint as pp
import re
import json
import requests  

url='https://sg.finance.yahoo.com/quote/1B0.SI/history?period1=1426780800&period2=1489939200&interval=div%7Csplit&filter=split&frequency=1mo'
soup = BeautifulSoup(requests.get(url).content)
script = soup.find("script",text=re.compile("root.App.main")).text
data = json.loads(re.search("root.App.main\s+=\s+(\{.*\})", script).group(1))
stores = data["context"]["dispatcher"]["stores"]
pp(stores)

如果您知道在哪里可以找到它,请告诉我。

谢谢!

【问题讨论】:

  • 如果你愿意,你有一个雅虎财经的模块,pypi.python.org/pypi/yahoo-finance
  • @AnthonyPrdal 谢谢,老实说我不知道​​ API,但我没有看到任何获取 Stock Splits 的方法。我也想解决这个问题,它应该有用在其他项目中对我来说。例如,这里引用的解决方案stackoverflow.com/questions/21445966/… 在很多情况下确实很强大,但在我这里没有这样的 iFrame :(
  • 您希望表格中显示日期为 2016 年 10 月 11 日和 2016 年 2 月 25 日的信息吗?

标签: python json web-scraping yahoo-finance


【解决方案1】:

我的猜测是您可以使用 selenium 来做到这一点,因此。

>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get('https://sg.finance.yahoo.com/quote/1B0.SI/history?period1=1426780800&period2=1489939200&interval=div%7Csplit&filter=split&frequency=1mo')
>>> driver.get('https://sg.finance.yahoo.com/quote/1B0.SI/history?period1=1426780800&period2=1489939200&interval=div%7Csplit&filter=split&frequency=1mo')
>>> tableRows = driver.find_elements_by_xpath('//tr')
>>> len(tableRows)
5
>>> tableRows[1].text
'Date Open High Low Close Adj close* Volume'
>>> tableRows[2].text
'Oct 11, 2016 2/1 Stock split'
>>> tableRows[3].text
'Feb 25, 2016 2/1 Stock split'

请特别注意,我必须加载页面两次。第一次加载失败。您可以在 selenium 文档中了解如何处理这种意外情况。 (使用try-except 而不是asssert。)抓取此页面时面临的主要困难是看不到HTML。我假设所需的内容将在表格中,并且该假设被证明是正确的。

【讨论】:

  • 谢谢,这正是我想要的。综上所述,HTML标签的盲搜索有没有小窍门?
  • 在这种情况下,您也许可以使用无头浏览器执行此操作,但事实证明这是不必要的。
  • 我刚刚学到了一种方法。请参阅stackoverflow.com/questions/43183736/…
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2020-09-10
  • 2017-01-14
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
相关资源
最近更新 更多