Python 将url解码为utf-8-sig时起始字节无效
代码如下:Python 将url解码为utf-8-sig时起始字节无效,python,web-scraping,Python,Web Scraping,代码如下: for page in forumPages: try: req = Request(page, headers={'User-Agent': 'Mozilla/5.0'}) sock = urlopen(req).read().decode("utf-8-sig") soup = BeautifulSoup(sock, 'html.parser') pageThreads = soup.findAll('ol'
for page in forumPages:
try:
req = Request(page, headers={'User-Agent': 'Mozilla/5.0'})
sock = urlopen(req).read().decode("utf-8-sig")
soup = BeautifulSoup(sock, 'html.parser')
pageThreads = soup.findAll('ol',{"class":"threads"})
print(len(pageThreads))
except Exception as ex:
pass
我得到了错误的答案
起始字节无效
如何解决异常,使我可以有有效的文本应用
执行
urlopen(req).read()
会给出\xef\xbb\xbf显示的文件的开头看起来确实是unicode字节顺序标记的UTF-8版本,因此您的解码方法是正确的。显然,文件的其余部分包含无效的utf-8。由于您无法控制正在刮取的输入的质量,因此可以像这样抑制错误,以便继续:
text = urlopen(req).read().decode("utf-8-sig", errors="replace")
这将用一个特殊的符号替换问题区域,以便您可以看到问题出现的地方。或者使用errors=“ignore”
使它们消失。我尝试应用该解决方案,但异常是相同的,您得到异常的无效起始字节在哪里?问题似乎不在代码的开头;但稍后它可能不是有效的utf-8。在166300位置附近的文本中有一些有趣的开始引号。尝试urlopen(req).read().decode(“utf-8-sig”,“忽略”)
@alexis solution