Python 请求编码的模块日志记录



我正在使用python并请求模块==2.18.4

在对一些数据进行请求爬网时,我使用日志记录模块进行调试。

我希望日志看起来像这样:

[DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290
[DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290
[DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290  

但我明白这个:

[DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290
[DEBUG] 2018-01-25 03:15:36,974 EUC-JP Japanese prober hit error at byte 1765
[DEBUG] 2018-01-25 03:15:36,990 EUC-KR Korean prober hit error at byte 1765
[DEBUG] 2018-01-25 03:15:36,994 CP949 Korean prober hit error at byte 1765
[DEBUG] 2018-01-25 03:15:37,009 EUC-TW Taiwan prober hit error at byte 1765
[DEBUG] 2018-01-25 03:15:37,036 utf-8 not active
[DEBUG] 2018-01-25 03:15:37,036 SHIFT_JIS Japanese confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,036 EUC-JP not active
[DEBUG] 2018-01-25 03:15:37,036 GB2312 Chinese confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,036 EUC-KR not active
[DEBUG] 2018-01-25 03:15:37,036 CP949 not active
[DEBUG] 2018-01-25 03:15:37,036 Big5 Chinese confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,036 EUC-TW not active
[DEBUG] 2018-01-25 03:15:37,036 windows-1251 Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 KOI8-R Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 ISO-8859-5 Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 MacCyrillic Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 IBM866 Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 IBM855 Russian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 ISO-8859-7 Greek confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 windows-1253 Greek confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 ISO-8859-5 Bulgairan confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 windows-1251 Bulgarian confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 TIS-620 Thai confidence = 0.01
[DEBUG] 2018-01-25 03:15:37,038 ISO-8859-9 Turkish confidence = 0.47949350706
[DEBUG] 2018-01-25 03:15:37,038 windows-1255 Hebrew confidence = 0.0
[DEBUG] 2018-01-25 03:15:37,038 windows-1255 Hebrew confidence = 0.0
[DEBUG] 2018-01-25 03:15:37,038 windows-1255 Hebrew confidence = 0.0
...

我不希望在日志中进行这种编码。如何删除它们?

尝试将模块chardet.charsetprober的日志记录级别设置为高于 DEBUG 的级别(例如。信息(。

logger = logging.getLogger('chardet.charsetprober')
logger.setLevel(logging.INFO)

我遇到了同样的问题,并发现这些来自chardet.charsetprober模块的额外日志。

若要禁止显示这些日志,请将其放在导入之后。

logging.getLogger('chardet.charsetprober').setLevel(logging.INFO)

这不会从模块chardet.charsetprober打印任何DEBUG级消息,并且您只会收到所需的日志消息。

希望对您有所帮助!

我认为这个问题与r.text有关(返回responsetext属性(。由于requests不知道具体的编码,因此必须尝试一下,因此记录了长列表。为了避免这种情况,您可以在访问r.text之前将日志记录级别设置得更高(如INFO(,或者指定编码(r.encoding='utf-8'或任何您喜欢的编码(。

response.content.decode('ISO-8859-1')将其设置为混合字符集解码,为我工作

不确定我是否正确理解了您的问题,为什么您不能将此消息分离到不同的日志记录级别。

如其他答案中所述,当您调用r.text字段时,请求库会尝试猜测文本的编码。

在某些情况下,您可以使用r.content字段(二进制响应内容(而不是r.text来避免此猜测过程。

最新更新