我正在研究使用 request 模块执行对网站的获取/发布的现有python代码。
当将代理传递给脚本时,python代码还允许使用代理,否则不使用代理。
我的问题与使用需要身份验证的代理有关。
proxy = user:password@ip:port
self.s = requests.Session()
if proxy != "":
self.proxies = {
"http": "http://" + proxy,
"https": "https://" + proxy
}
self.s.proxies.update(proxies)
self.s.get('http://checkip.dyndns.org')
在上面的代码中,如果配置了代理,则每个 get 都会被拒绝,因为没有提供身份验证。
我找到了一个暗示使用HTTPProxyAuth的解决方案。
这是我找到的解决方案:
import requests
s = requests.Session()
proxies = {
"http": "http://ip:port",
"https": "https://ip:port"
}
auth = HTTPProxyAuth("user", "pwd")
ext_ip = s.get('http://checkip.dyndns.org', proxies=proxies, auth=auth)
print ext_ip.text
我的问题是:是否可以全局设置代理授权而不是修改代码中的每个 s.get ?因为有时脚本可以在没有代理的情况下使用,有时可以与代理一起使用。
谢谢!
最好的问候, 费德里科
答案 0 :(得分:2)
我找到了有关如何全局设置代理身份验证的解决方案:
import requests
import urllib2
import re
from requests.auth import HTTPProxyAuth
s = requests.Session()
proxies = {
"http": "http://185.165.193.208:8000",
"https": "https://185.165.193.208:8000"
}
auth = HTTPProxyAuth("gRRT7n", "NMu8g0")
s.proxies = proxies
s.auth = auth # Set authorization parameters globally
ext_ip = s.get('http://checkip.dyndns.org')
print ext_ip.text
BR, 费德里科