Python Requests 库 InvalidHeader 错误:请求头包含无效字符或空格
C:\Users\Administrator\Desktop\lxy>C:/Python3/python.exe c:/Users/Administrator/Desktop/lxy/3.py
DevTools listening on ws://127.0.0.1:9669/devtools/browser/5e900f69-d0fb-4830-9f8c-aaa696210a7c
Traceback (most recent call last):
File "c:/Users/Administrator/Desktop/lxy/3.py", line 79, in
C:\Users\Administrator\Desktop\lxy>[5928:6416:0613/160050.292:ERROR:chrome_browser_main_extra_parts_metrics.cc(226)] crbug.com/1216328: Checking Bluetooth availability started. Please report if there is no report that this ends. [5928:6416:0613/160050.393:ERROR:chrome_browser_main_extra_parts_metrics.cc(229)] crbug.com/1216328: Checking Bluetooth availability ended. [5928:6416:0613/160050.396:ERROR:chrome_browser_main_extra_parts_metrics.cc(232)] crbug.com/1216328: Checking default browser status started. Please report if there is no report that this ends. [5928:6416:0613/160050.459:ERROR:chrome_browser_main_extra_parts_metrics.cc(236)] crbug.com/1216328: Checking default browser status ended.
是什么错误内容: 该错误是由于请求头中包含了无效的字符或空格导致的。具体来说,这里的错误信息指出了请求头中的某个值包含了无效的前导空格或保留字符,例如回车符。需要检查请求头中的所有值,确保它们都是有效且合法的。
解决方法:
- **检查代码:**仔细检查代码中设置的请求头,特别是 User-Agent 等字段,确保没有包含无效字符或空格。
- **查看请求头:**使用调试工具或打印语句查看发送的实际请求头,确认是否有错误字符或空格。
- **使用字符串处理方法:**可以使用 Python 的字符串处理方法,例如
strip()和replace(),来去除请求头中的空格或特殊字符。 - **使用正则表达式:**如果需要进行更复杂的字符验证,可以使用正则表达式来匹配和过滤请求头中的非法字符。
示例:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'
}
# 去除 User-Agent 中的前导空格
headers['User-Agent'] = headers['User-Agent'].strip()
总结: Requests 库的 InvalidHeader 错误通常是由于请求头包含了无效字符或空格导致的。通过检查代码、查看请求头、使用字符串处理方法或正则表达式等手段,可以有效地解决此类问题。确保请求头符合 HTTP 协议规范,可以避免此类错误的发生。
原文地址: https://www.cveoy.top/t/topic/oBi9 著作权归作者所有。请勿转载和采集!