修复 requests session TypeError: __init__() got an unexpected keyword argument 'headers'
问题:
你尝试使用类似这样的自定义 HTTP 头集初始化 Python requests 会话:
requests_session_fix.py
s = requests.Session(headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"
})但你只看到此堆栈跟踪:
RequestsSession.py
File "RequestsSession.py", line 30, in translate
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"
TypeError: __init__() got an unexpected keyword argument 'headers'解决方案
你不能在 requests.Session(...) 构造函数中使用 headers=... 参数。
使用 s.headers.update({...}) 代替:
requests_session_fix.py
s = requests.Session()
s.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"
})Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow