Python 子线程里创建 BeautifulSoup 对象会在终端打印encoding error : input conversion failed due to input error, 主线程里面一切正常。
感觉应该是 lxml 的问题,但是没找到怎么解决,求解惑
就几个特定的网页会出现这个问题,比如 http://zhuanlan.sina.com.cn/
下面这个代码可以用来复现
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('在主线程中执行 test')
test()
print('在子线程中执行 test')
t = Thread(target=test)
t.start()
t.join()
输出如下
在主线程中执行 test
在子线程中执行 test
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
     1 
                    
                    seanzhao      2018-03-26 19:03:05 +08:00 
                    
                    把你的解析那段替换成以下代码,不是线程问题,是编码问题。 
                soup = BeautifulSoup(r.content.decode('ISO-8859-1'),'lxml')  | 
            
     2 
                    
                    eggshell   OP  | 
            
     3 
                    
                    kenzh      2018-03-26 20:24:38 +08:00 
                    
                    试下  r.content.decode('gb2312', 'ignore').encode('gb2312') 
                 | 
            
     6 
                    
                    holajamc      2018-03-26 21:42:40 +08:00 
                    
                    import requests 
                from bs4 import BeautifulSoup from threading import Thread def test(): r = requests.get('http://zhuanlan.sina.com.cn/') print(r.encoding) soup = BeautifulSoup(r.content.decode('utf-8', 'ignore'), 'lxml') print('在主线程中执行 test') test() print('在子线程中执行 test') t = Thread(target=test) t.start() t.join() 注意看加的那一行的输出呦~  | 
            
     7 
                    
                    holajamc      2018-03-26 21:43:47 +08:00 
                    
                    
                 | 
            
     8 
                    
                    eggshell   OP @holajamc 加的那一行的输出是 ISO-8859-1,应该是 response header 里没有编码信息,然后 requests 按照标准默认用错误的 ISO-8859-1 解码了,但是还是没搞懂他这个多线程是怎么回事。。 
                 | 
            
     10 
                    
                    TimePPT   PRO soup = BeautifulSoup(r.content, 'lxml', from_encoding=r.encoding) 
                 |