使用 Python 3 从雅虎财经网站检索股票信息
Using Python 3 to Retrieve Stock Information From Yahoo Finance Site
我一直在尝试移植一个脚本,该脚本将从 Yahoo Finance 网站请求基本数据,但我想查找特定项目而不是整个报告,例如市净率。所以,我遵循了 Sentdex 的教程,了解如何做到这一点。问题是示例代码是为 Python 2.7 编写的,我正在尝试使其适用于 Python 3,当然通过添加更多功能对其进行扩展。
目前情况如下:
import time
import urllib
import urllib.request
sp500short = ['a', 'aa', 'aapl', 'abbv', 'abc', 'abt', 'ace', 'aci', 'acn', 'act', 'adbe', 'adi', 'adm', 'adp']
def yahooKeyStats(stock):
try:
sourceCode = urllib.request.urlopen('http://finance.yahoo.com/q/ks?s='+stock).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
print ('price to book ratio:'),stock,pbr
except Exception as e:
print ('failed in the main loop'),str(e)
for eachStock in sp500short:
yahooKeyStats(eachStock)
time.sleep(1)
我几乎可以肯定问题出在 pbr 变量定义上,在它的拆分部分。该:
Price/Book (mrq):</td><td class="yfnc_tabledata1">
还有……:
</td>
...只是我正在寻找的分隔符,实际值在列出的这两个项目之间 above.But,到目前为止它只在执行时给我异常消息它。
任何帮助将不胜感激。
干杯,
看起来 urllib.request.urlopen
和 .read()
正在返回类型为 bytes
的数据。
来自 python 文档:
Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the http server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding.
拆分方法在这里失败了。尝试在 .read()
之后附加 .decode()
。问题是您试图用字符串拆分类型为 bytes
的 sourceCode
变量。解码 sourceCode
会将其从字节转换为字符串。或者,您可以 .encode()
两个分隔符。
我一直在尝试移植一个脚本,该脚本将从 Yahoo Finance 网站请求基本数据,但我想查找特定项目而不是整个报告,例如市净率。所以,我遵循了 Sentdex 的教程,了解如何做到这一点。问题是示例代码是为 Python 2.7 编写的,我正在尝试使其适用于 Python 3,当然通过添加更多功能对其进行扩展。
目前情况如下:
import time
import urllib
import urllib.request
sp500short = ['a', 'aa', 'aapl', 'abbv', 'abc', 'abt', 'ace', 'aci', 'acn', 'act', 'adbe', 'adi', 'adm', 'adp']
def yahooKeyStats(stock):
try:
sourceCode = urllib.request.urlopen('http://finance.yahoo.com/q/ks?s='+stock).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
print ('price to book ratio:'),stock,pbr
except Exception as e:
print ('failed in the main loop'),str(e)
for eachStock in sp500short:
yahooKeyStats(eachStock)
time.sleep(1)
我几乎可以肯定问题出在 pbr 变量定义上,在它的拆分部分。该:
Price/Book (mrq):</td><td class="yfnc_tabledata1">
还有……:
</td>
...只是我正在寻找的分隔符,实际值在列出的这两个项目之间 above.But,到目前为止它只在执行时给我异常消息它。
任何帮助将不胜感激。 干杯,
看起来 urllib.request.urlopen
和 .read()
正在返回类型为 bytes
的数据。
来自 python 文档:
Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the http server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding.
拆分方法在这里失败了。尝试在 .read()
之后附加 .decode()
。问题是您试图用字符串拆分类型为 bytes
的 sourceCode
变量。解码 sourceCode
会将其从字节转换为字符串。或者,您可以 .encode()
两个分隔符。