看来Google财经修改了其网址/端点,并且该
googlefinance软件包尚未更新以反映所做的更改。
由于大多数更改对于最终用户而言都是相当不透明的(并且您正在使用的库在两年内都没有更新),因此您最好自己处理原始的Google Finance响应。
Google财经端点
您可以通过以下URL检索有关特定股票代码的信息:
https://finance.google.com/finance?output=json&q=TICKER_SYMBOL
响应
Google财经以这种格式返回JSON结果
n// [n{n"symbol" : "AAPL",n"exchange" : "NASDAQ",n"id": "22144",n"t" : "AAPL",n"e" : "NASDAQ",n"name" : "Apple Inc."n, "f_reuters_url" : "http:\x2F\x2Fstocks.us.reuters.com\x2Fstocks\x2Fratios.asp?rpc=66\x26symbol=AAPL.O",n"f_recent_quarter_date" : "Q3 (Jul \x2717)",n"f_annual_date" : "2016",n"f_ttm_date" : "2015",n"financials" : ... a lot more stuff ...[n]n}]n'无法使用Python的JSON解析器按原样加载它
//,因为它具有前导符,并将所有内容包装在内
[]。它还具有需要解码的各种字符串中的Unipre转义字符。
完整的代码和解析
我将为此使用
requests模块,但是如果您想使用内置
urllib模块的示例,我也可以展示一下。
import jsonimport requestsrsp = requests.get('https://finance.google.com/finance?q=AAPL&output=json')if rsp.status_pre in (200,): # This magic here is to cut out various leading characters from the JSON # response, as well as trailing stuff (a terminating ']n' sequence), and then # we depre the escape sequences in the response # This then allows you to load the resulting string # with the JSON module. fin_data = json.loads(rsp.content[6:-2].depre('unipre_escape')) # print out some quote data print('Opening Price: {}'.format(fin_data['op'])) print('Price/Earnings Ratio: {}'.format(fin_data['pe'])) print('52-week high: {}'.format(fin_data['hi52'])) print('52-week low: {}'.format(fin_data['lo52']))这将输出:
Opening Price: 162.71Price/Earnings Ratio: 18.4352-week high: 164.9452-week low: 102.53
完全自动收录器JSON中包含的数据比我输出的要多得多,因此由您决定如何使用其中的任何数据。
备择方案
或者,您可以使用该
yahoo-finance模块,因为Yahoo仍然提供了真实的财务API,因此可能不太可能出现此类问题。



