鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python  Linux/ Python3在子線程中新建BeautifulSoup對象針對特定網(wǎng)頁會(huì)出現(xiàn)en

Python3在子線程中新建BeautifulSoup對象針對特定網(wǎng)頁會(huì)出現(xiàn)encoding error,主線程中則沒有異常

如題,使用Python requests和BeautifulSoup,編寫一個(gè)簡單的函數(shù)test從網(wǎng)址生成soup對象(見下面的例子)。如果在主線程里面直接調(diào)用那么一切正常,但是如果在子線程里面調(diào)用這個(gè)函數(shù)就會(huì)出現(xiàn)encoding error : input conversion failed due to input error, bytes 0x95 0x50 0x22 0x20 這樣的日志信息, 而且是直接輸出到stdout的,沒有拋出異常也就沒法捕獲。
請問有什么方法可以解決嗎?

下面是一個(gè)可以復(fù)現(xiàn)的例子。

from threading import Thread

import requests
from bs4 import BeautifulSoup

def test():
    r = requests.get('http://zhuanlan.sina.com.cn/')
    soup = BeautifulSoup(r.content,'lxml')

print('在主線程中執(zhí)行test')
test()

print('在子線程中執(zhí)行test')
t = Thread(target=test)
t.start()
t.join()

輸出內(nèi)容如下

在主線程中執(zhí)行test
在子線程中執(zhí)行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
回答
編輯回答
只愛你
r.encoding = 'gbk'
soup = BeautifulSoup(r.text, 'lxml')
2017年4月1日 11:00