我正试着从FiveThirtyEight上获取NBA的比赛预测。我通常使用urllib2和BeautifulSoup从网络上抓取数据。然而,从这个过程中返回的html非常奇怪。它是一个字符串,例如"\x82\xdf\x97S\x99\xc7\x9d“。我无法将其编码为常规文本。下面是我的代码:
from urllib2 import urlopen
html = urlopen('http://projects.fivethirtyeight.com/2016-nba-picks/').read()这种方法适用于538上的其他网站和其他页面,但不适用于这个网站。
编辑:我尝试使用以下命令来解码字符串
html.decode('utf-8')方法定位到了here,但我得到了以下错误消息:
UnicodeDecodeError:'utf8‘编解码器无法对位置1中的字节0x8b进行解码:起始字节无效
发布于 2016-04-14 11:06:45
默认情况下,该页面似乎返回gzipped数据。下面的代码应该可以解决这个问题:
from urllib2 import urlopen
import zlib
opener = urlopen('http://projects.fivethirtyeight.com/2016-nba-picks/')
if 'gzip' in opener.info().get('Content-Encoding', 'NOPE'):
    html = zlib.decompress(opener.read(), 16 + zlib.MAX_WBITS)
else:
    html = opener.read()结果在BeautifulSoup中没有任何问题。
在尝试推断Python url库问题的原因时,HTTP头(由上面的.info()返回)通常很有用。
https://stackoverflow.com/questions/36612721
复制相似问题