我试图从谷歌财经获取一些信息,但我收到此错误
AttributeError:“HTTPResponse”对象没有属性“split”
这是我的Python代码:
import urllib.request
import urllib
from bs4 import BeautifulSoup
symbolsfile = open("Stocklist.txt")
symbolslist = symbolsfile.read()
thesymbolslist = symbolslist.split("\n")
i=0
while i<len (thesymbolslist):
theurl = "http://www.google.com/finance/getprices?q=" + thesymbolslist[i] + "&i=10&p=25m&f=c"
thepage = urllib.request.urlopen (theurl)
print(thesymbolslist[i] + " price is " + thepage.split()[len(thepage.split())-1])
i= i+1
问题的原因
这是因为urllib.request.urlopen (theurl)
返回表示连接的对象,而不是字符串。
解决方案
要从此连接读取数据并实际获取字符串,您需要执行以下操作
thepage = urllib.request.urlopen(theurl).read()
然后你的代码的其余部分应该自然地遵循。
解决方案的附录
有时,字符串本身包含无法识别的字符编码字形,在这种情况下,Python 将其转换为字节串 https://stackoverflow.com/questions/22824539/what-is-a-python-bytestring.
处理这个问题的正确方法是找到正确的字符编码并使用它将字节串解码为常规字符串,如下所示这个问题 https://stackoverflow.com/questions/36877016/typeerror-str-does-not-support-the-buffer-interface-in-html2text/36879764#36879764:
thepage = urllib.request.urlopen(theurl)
# read the correct character encoding from `Content-Type` request header
charset_encoding = thepage.info().get_content_charset()
# apply encoding
thepage = thepage.read().decode(charset_encoding)
有时可以安全地假设字符编码是utf-8
, 在这种情况下
thepage = urllib.request.urlopen(theurl).read().decode('utf-8')
确实经常有效。如果不出意外的话,这是一个统计上很好的猜测。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)