使用python3从Yahoo Finance Si检索股票信息

2024-05-14 18:01:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试移植一个脚本,它将从雅虎财经网站请求基本数据,但我想寻找具体的项目,而不是整个报告,例如市盈率。所以,我遵循了Sentdex关于如何做到这一点的教程。问题是,示例代码是为Python2.7编写的,我正试图使其适用于Python3,当然还可以通过添加更多特性来扩展它。在

以下是目前的情况:

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变量定义上,在它的拆分部分。以下内容:

^{pr2}$

还有…:

</td>

…只是一种分隔符,因为我要找的是,实际值,在列出的两个项目之间上面。但是,到目前为止,它只在执行时给我一个异常消息。在

任何帮助都将不胜感激。 干杯


Tags: 项目inimporttimerequeststockurllibtd
1条回答
网友
1楼 · 发布于 2024-05-14 18:01:19

看起来urllib.request.urlopen和{}返回的数据类型为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.

split方法在这里失败了。试着在.read()后面加上.decode()。问题是您试图将sourceCode变量拆分为bytes类型的一个字符串。解码sourceCode将把它从字节转换成字符串。或者,您可以.encode()两个分隔符。在

bytes.decode

相关问题 更多 >

    热门问题