我希望从雅虎财经获得scrapy的最大历史价格数据.
这是fb(facebook)最大历史价格数据的网址.
https://query1.finance.yahoo.com/v7/finance/download/FNMA?period1=221115600&period2=1508472000&interval=1d&events=history&crumb=1qRuQKELxmM
为了写一个股票价格网络爬虫,我无法解决两个问题.
1.如何获得论证期限1?
您可以在网页上手动获取,只需单击最大值.
如何用python代码获取参数?
不同的股票具有不同的期间1值.
2.如何自动创建参数crumb = 1qRuQKELxmM,不同的股票具有不同的crumb值?
这是我的股票最大历史数据与scrapy框架.
import scrapy
class TestSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["finance.yahoo.com"]
def __init__(self, *args, **kw):
self.timeout = 10
def start_requests(self):
stockName = get-it and ommit the codes
for stock in stockName:
period1 = how to fill it
crumb = how to fill it
per_stock_max_data = "https://query1.finance.yahoo.com/v7/finance\
download/"+stock+"?period1="+period1+"&period2=1508472000&\
interval=1d&events=history&"+"crumb="crumb
yield scrapy.Request(per_stock_max_data,callback=self.parse)
def parse(self, response):
content = response.body
target = response.url
#do something
如何在我的web scrawler框架中填写上面的空白?
最佳答案 据我了解,您想要下载特定代码的所有可能数据.所以要做到这一点,如果你提供0代替period1,那么你实际上不需要提供period1参数,然后Yahoo API将默认值设置为最早的日期.
要使用您在问题中显示的方式下载报价,我们很遗憾不得不处理cookie.我会让自己在不使用Scrapy的情况下提供解决方案,只需要自动收报机:
import re
import time
import requests
def get_yahoo_ticker_data(ticker):
res = requests.get('https://finance.yahoo.com/quote/' + ticker + '/history')
yahoo_cookie = res.cookies['B']
yahoo_crumb = None
pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
for line in res.text.splitlines():
m = pattern.match(line)
if m is not None:
yahoo_crumb = m.groupdict()['crumb']
cookie_tuple = yahoo_cookie, yahoo_crumb
current_date = int(time.time())
url_kwargs = {'symbol': ticker, 'timestamp_end': current_date,
'crumb': cookie_tuple[1]}
url_price = 'https://query1.finance.yahoo.com/v7/finance/download/' \
'{symbol}?period1=0&period2={timestamp_end}&interval=1d&events=history' \
'&crumb={crumb}'.format(**url_kwargs)
response = requests.get(url_price, cookies={'B': cookie_tuple[0]})
如果您确实需要最早的日期,那么您可以使用上面的代码并从响应中提取第一个日期.
编辑
我知道网络抓取不是一个有效的选择,但它是我们唯一的选择,因为雅虎已经撤回了所有的API.您可能会找到一些第三方解决方案,但所有这些解决方案都在其源代码中使用抓取功能,并且它们会为数据添加一些额外的转换,从而降低整体效率.