我写了一个示例代码:
import requests
from bs4 import BeautifulSoup
from threading import Thread
def test():
r = requests.get('http://zhuanlan.sina.com.cn/')
soup = BeautifulSoup(r.content,'lxml')
print('run test on main thread')
test()
print('run test on child thread')
t = Thread(target=test)
t.start()
t.join()
输出为:
run test on main thread
run test on child thread
encoding error : input conversion failed due to input error, bytes 0x95 0x50 0x22 0x20
encoding error : input conversion failed due to input error, bytes 0x95 0x50 0x22 0x20
encoding error : input conversion failed due to input error, bytes 0x95 0x50 0x22 0x20
我编写了一个测试功能,然后在主线程和子线程中运行它。如输出所示,测试功能以子线程打印encoding error: input conversion failed due to input error
运行,我无法阻止它。为什么会发生这种情况?
我遇到了这个问题,想在 @real_kappa_guy的解决方案上构建,这是正确的想法,但可能需要更多的解释。
我相信错误来自BeautifulSoup确定文档编码的尝试。它使用称为" Unicode"的库要检测编码,但通常该文档不包含足够的信息来准确确定编码。这些情况可能导致编码错误正在打印出来。
修复程序确实是用文档的原始编码为任何内容(iso-8859-1
是一个示例(来指定from_encoding
参数。您可以从响应中以编程方式获取编码:
soup = BeautifulSoup(r.content, 'lxml', from_encoding=r.encoding)
Beautifulsoup的文档中还有更多信息。
我建议这来自XML解析器...因为使用HTML解析器,错误消失了...
def test():
r = requests.get('http://zhuanlan.sina.com.cn/')
soup = BeautifulSoup(r.text, 'html.parser')
我获得了这个:
run test on main thread
run test on child thread
现在已经很晚了,但是只要有人遇到这个问题,这对我来说是一个障碍:
soup = BeautifulSoup(r.content,'lxml',from_encoding="iso-8859-1")