代码如下:
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
我收到错误如下
invalid start byte
如何解决异常,以便我可以有有效的文本来应用 SOUP。
正在做urlopen(req).read()
给出\xef\xbb\xbf<!DOCTYPE html PUBLIC ...
我尝试的页面是 https://www.siasat.pk/forum/forumdisplay.php?22-Siasi-Discussion/page1
我尝试过申请this :
sock = urlopen(req).read().decode("utf-8-sig").encode("utf-8")
但异常(exception)是相同的
最佳答案
您显示的文件的开头确实似乎是 unicode 字节顺序标记的 UTF-8 版本,因此您的解码方法是正确的。显然文件的其余部分在某处包含无效的 utf-8 。由于您无法控制正在抓取的输入的质量,因此您可以像这样抑制错误,以便继续:
text = urlopen(req).read().decode("utf-8-sig", errors="replace")
这将用特殊符号替换问题区域,以便您可以看到问题出现的位置。或者使用 errors="ignore"
让它们消失。
关于python - 将 url 解码为 utf-8-sig 时起始字节无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271860/