Python 子线程里创建 BeautifulSoup 对象会在终端打印 encoding error,主线程就没问题,求解惑

2018-03-26 18:50:21 +08:00
 eggshell

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
5292 次点击
所在节点    Python
11 条回复
seanzhao
2018-03-26 19:03:05 +08:00
把你的解析那段替换成以下代码,不是线程问题,是编码问题。
soup = BeautifulSoup(r.content.decode('ISO-8859-1'),'lxml')
eggshell
2018-03-26 19:47:01 +08:00
@seanzhao 谢谢啦,不过应该不是编码的问题,试了下子线程里面还是会打印 encoding error, 主线程还是正常的
![截图]( )
kenzh
2018-03-26 20:24:38 +08:00
试下 r.content.decode('gb2312', 'ignore').encode('gb2312')
seanzhao
2018-03-26 20:30:18 +08:00
@eggshell 好吧,给你的那段代码,我已经在本机测试通过的,不知道你那边是什么个情况。
eggshell
2018-03-26 20:42:00 +08:00
@kenzh 这样就可以了。。 但是之前为什么主线程里面跑就正常,子线程里就不行呢, 好迷啊= =
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()

注意看加的那一行的输出呦~
holajamc
2018-03-26 21:43:47 +08:00
eggshell
2018-03-27 00:15:47 +08:00
@holajamc 加的那一行的输出是 ISO-8859-1,应该是 response header 里没有编码信息,然后 requests 按照标准默认用错误的 ISO-8859-1 解码了,但是还是没搞懂他这个多线程是怎么回事。。
holajamc
2018-03-27 09:39:17 +08:00
@eggshell 看起来是 lxml 的问题了 我试过用 html.parser 和 html5lib 都没有问题诶
TimePPT
2018-03-27 10:52:55 +08:00
soup = BeautifulSoup(r.content, 'lxml', from_encoding=r.encoding)
TimePPT
2018-03-27 13:42:17 +08:00
@TimePPT 囧,试了下不行,soup 的编码还是有问题 orz

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/441577

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX