Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将url解码为utf-8-sig时起始字节无效_Python_Web Scraping - Fatal编程技术网

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