在使用 Python 的 requests
库发送 HTTP 请求时,如果遇到如下错误:
TypeError: __init__() got an unexpected keyword argument 'proxies'
这通常意味着你传递给 requests
函数的参数名称有误,或者你使用的 requests
库版本过旧,不支持 proxies
参数。以下是可能的原因及解决方法:
确保你在调用 requests
函数时使用了正确的参数名称。proxies
是一个关键字参数,应该这样使用:
import requests
proxies = {
'http': 'http://代理服务器地址:端口',
'https': 'https://代理服务器地址:端口',
}
response = requests.get('http://目标网址', proxies=proxies)
常见错误:
proxy
(单数)而不是 proxies
(复数)。requests
库版本proxies
参数在 requests
库中是支持的,但如果你使用的是非常旧的版本,可能会遇到兼容性问题。建议升级 requests
到最新版本:
pip install --upgrade requests
以下是一个完整的示例,展示如何使用 proxies
参数:
import requests
# 定义代理服务器
proxies = {
'http': 'http://10.10.1.10:3128', # 替换为你的代理服务器地址和端口
'https': 'http://10.10.1.10:1080',
}
# 发送 GET 请求
try:
response = requests.get('http://www.example.com', proxies=proxies, timeout=5)
print(response.text)
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
proxies
参数:
export HTTP_PROXY=http://10.10.1.10:3128 export HTTPS_PROXY=http://10.10.1.10:1080
然后在代码中直接使用 requests
,它会自动使用这些代理设置。如果以上方法都无法解决问题,建议检查以下几点:
proxies
参数是在正确的函数调用中传递的,例如 requests.get()
或 requests.post()
,而不是在创建 Session
对象时。requests
的功能,确保在内部正确处理了 proxies
参数,没有误用或覆盖。TypeError: __init__() got an unexpected keyword argument 'proxies'
错误通常是由于参数名称错误或 requests
库版本过旧引起的。通过检查参数名称、升级库版本以及确保正确使用 proxies
参数,可以解决此问题。如果问题依然存在,请提供更多的代码示例,以便进一步诊断。
领取专属 10元无门槛券
手把手带您无忧上云