当使用python对网页进行屏幕抓取时,必须知道页面的字符编码.如果你得到的字符编码错误,你的输出就会搞砸了.
人们通常使用一些基本技术来检测编码.它们使用标题中的字符集或元标记中定义的字符集,或者使用编码检测器(不关心元标记或标题).通过仅使用这些技术,有时您将无法获得与浏览器相同的结果.
浏览器这样做:
(嗯......至少这是我认为大多数浏览器都这样做的方式.文档非常缺乏.)
我正在寻找的是一个可以像浏览器一样决定页面字符集的库.我确信我不是第一个需要妥善解决这个问题的人.
美丽的汤按优先级顺序尝试以下编码,将您的文档转换为Unicode:
我正在尝试从Google财经获取一些信息,但出现此错误
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
Run Code Online (Sandbox Code Playgroud)