我正在尝试从Google财经获取一些信息,但出现此错误
AttributeError: 'HTTPResponse' object has no attribute 'split'
这是我的python代码:
import urllib.request
import urllib
from bs4 import BeautifulSoup
symbolsfile = open("Stocklist.txt")
symbolslist = symbolsfile.read()
thesymbolslist = symbolslist.split("
")
i=0
while i
theurl ="/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
您想在这里做什么? thepage.split()[len(thepage.split())-1])
我试图将页面放入列表中,然后从该列表中获取最后一个属性并进行打印。
您需要从thepage中获取read()以获得实际的字符串。
问题的原因
这是因为urllib.request.urlopen (theurl)返回表示连接的对象,而不是字符串。
解决方案
要从此连接读取数据并实际获取字符串,您需要
thepage = urllib.request.urlopen(theurl).read()
然后其余的代码应该自然地遵循。
解决方案附录
有时,字符串本身包含无法识别的字符编码字形,在这种情况下,Python会将其转换为字节串。
解决该问题的正确方法是找到正确的字符编码,并使用它来将字节字符串解码为常规字符串,如以下问题所示:
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')
确实比不经常工作。如果没有别的,这是一个统计上不错的猜测。
一旦我这样做,它给了我这个错误:TypeError:无法将字节对象隐式转换为str
这是因为您收到的字符串的编码不是Python可以理解的。给我一点时间来解决问题。
您的解决方案更加健壮,因为它不依赖于源编码,因此OP:最好将其标记为正确的答案:)
查看文档可能会节省您将来的时间。它说urlopen()方法返回一个具有read()方法的HTTPResponse对象。在Python 3中,您需要对源编码(在本例中为UTF-8)的输出进行解码。所以写
thepage = urllib.request.urlopen(theurl).read().decode('utf-8')
一旦我这样做,它给了我这个错误:TypeError:无法将字节对象隐式转换为str
Python 3?然后查看/questions/16699362/尝试thepage = urllib.request.urlopen(theurl).read().decode(utf-8)
修复它,谢谢
@le_m假定默认编码为utf-8-通常为true,但不一定是发送过来的编码。正确的方法是检查标头中的编码并将其应用。
@AkshatMahajan当然,您是对的,但是由于OP只是在查询,因此我们可以放心地假设使用UTF-8。
@le_m您会惊讶于Google用什么字符编码代替UTF-8 ...