当前位置: 移动技术网 > IT编程>脚本编程>Python > python中设置HTTP代理的方法

python中设置HTTP代理的方法

2017年12月21日  | 移动技术网IT编程  | 我要评论

佛山嘉邦郭斌,fuel.service.exe,世界卫生日

什么是HTTP代理

HTTP代理本质上是一个Web应用,它和其他普通Web应用没有根本区别。HTTP代理收到请求后,根据Header中Host字段的主机名和Get/POST请求地址综合判断目标主机,建立新的HTTP请求并转发请求数据,并将收到的响应数据转发给客户端。

python中设置HTTP代理

使用get方法请求,在python程序中设置HTTP代理有两种方法,一种是urllib,一种是requests。

192.168.1.2 Web服务器
192.168.1.3 HTTP代理服务器,端口8080
方法一:urllib代理设置

url = "https://192.168.1.2" #web服务器

proxy_handler = urllib2.ProxyHandler({'http': 'https://192.168.1.3:8080/'})  #代理服务器
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)
proxy_auth_handler.add_password(None, 'https://192.168.1.3:8080', 'username', 'password')

opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
urllib2.install_opener(opener)

params={
        'time': time,
        'ip': ip
} #需要提交的参数
params=urllib.urlencode(params)
req=urllib2.Request(url = '%s%s%s' % (url,'?',params))
conn = urllib2.urlopen(req)
res=conn.read()
data=json.loads(res) #data是dict格式的,存储返回的结果
方法二:requests设置

params={
        'time': time,
        'ip': ip
} #需要提交的参数
response=requests.get('https://192.168.1.2',params=params,proxies={'http':'https://username:password@192.168.1.3:8080/'})
data=json.loads(response.text) #data是dict格式的,存储返回的结果

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网