【问题标题】:Creating a BeautifulSoup object in a child thread will print a encoding error在子线程中创建 BeautifulSoup 对象将打印编码错误
【发布时间】:2018-09-04 10:32:20
【问题描述】:

我写了一个示例代码:

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

我写了一个测试函数,在主线程和子线程中运行。如输出所示,测试函数在子线程 print encoding error: input conversion failed due to input error 中运行,我无法阻止它。为什么会这样?

【问题讨论】:

    标签: python multithreading beautifulsoup thread-safety lxml


    【解决方案1】:

    有点晚了,但万一有人再次遇到这种情况,这对我有用:

    soup = BeautifulSoup(r.content,'lxml',from_encoding="iso-8859-1")
    

    【讨论】:

      【解决方案2】:

      我遇到了这个问题,想在@real_kappa_guy 的解决方案的基础上进行构建,这是正确的想法,但可能需要更多解释。

      我相信错误来自 BeautifulSoup 尝试确定文档的编码。它使用一个名为“Unicode, Dammit”的库来检测编码,但文档通常不包含足够的信息来准确确定编码。这些情况会导致打印出编码错误。

      修复确实是使用文档的原始编码指定from_encoding 参数(iso-8859-1 是一个示例)。您可以从响应中以编程方式获取编码:

      soup = BeautifulSoup(r.content, 'lxml', from_encoding=r.encoding)
      

      BeautifulSoup 的文档here 中有更多信息。

      【讨论】:

        【解决方案3】:

        我建议这来自 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-20
          • 1970-01-01
          • 2019-09-24
          • 2016-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-23
          相关资源
          最近更新 更多