在python中,requests
使用代理要比urllib
好用太多,urllib还是有些交互性差。
HTTP代理
如果需要使用代理,你可以通过为任意请求方法提供 proxies
参数来配置单个请求:
import requests
proxies = {
"http": "http://10.10.1.10:3128","https": "http://10.10.1.10:1080",}
requests.get("http://example.org",proxies=proxies)
你也可以通过环境变量 HTTP_PROXY
和 HTTPS_PROXY
来配置代理。
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
$ python
>>> import requests
>>> requests.get("http://example.org")
若你的代理需要使用HTTP Basic Auth,可以使用 http://user:password@host/
语法:
proxies = {
"http": "http://user:pass@10.10.1.10:3128/",}
要为某个特定的连接方式或者主机设置代理,使用 scheme://hostname
作为 key, 它会针对指定的主机和连接方式进行匹配。
proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}
注意,代理 URL 必须包含连接方式。
socks5代理
import requests
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/67.0.3396.79 Safari/537.36'
}
proxies = {
"http": "socks5://127.0.0.1:1086",'https': 'socks5://127.0.0.1:1086'
}
url = 'https://www.google.com/search?q=python'
res = requests.get(url,headers=headers,proxies=proxies)
print(res)