Python中设置代理访问网络

记一下怕忘记,公司上网用的代理,一个Python写的小程序要在局域网正确设置的前提下才可以正常运行,这里在小程序内设置了代理就可以不用依赖电脑的设置正常运行。

proxyConfig = 'http://{}:{}@{}'.format(username, password, your_ip_address) # ip地址与端口之间用冒号分开
proxy_support=urllib.request.ProxyHandler({'http':proxyConfig})
opener = urllib.request.build_opener(proxy_support) 
urllib.request.install_opener(opener)
web = urlopen(url, data)
r = web.read()

原文:
python使用代理访问服务器主要有一下3个步骤:

1.创建一个代理处理器ProxyHandler:

proxy_support = urllib.request.ProxyHandler(),ProxyHandler是一个类,其参数是一个字典:{ '类型':'代理ip:端口号'}

什么是Handler?Handler也叫作处理器,每个handlers知道如何通过特定协议打开URLs,或者如何处理URL打开时的各个方面,例如HTTP重定向或者HTTP cookies。

2.定制、创建一个opener:

opener = urllib.request.build_opener(proxy_support)

什么是opener?python在打开一个url链接时,就会使用opener。其实,urllib.request.urlopen()函数实际上是使用的是默认的opener,只不过在这里我们需要定制一个opener来指定handler。

3a.安装opener

urllib.request.install_opener(opener)

install_opener 用来创建(全局)默认opener,这个表示调用urlopen将使用你安装的opener。

3b.调用opener
opener.open(url)

该方法可以像urlopen函数那样直接用来获取urls:通常不必调用install_opener,除了为了方便。

>>> proxy_support = urllib.request.ProxyHandler({'http':'115.32.41.100:80'})
>>> proxy_support
<urllib.request.ProxyHandler object at 0x0000000002EE74A8>
>>> opener = urllib.request.build_opener(proxy_support)
>>> opener
<urllib.request.OpenerDirector object at 0x0000000002F972B0>
>>> opener.handlers
[<urllib.request.ProxyHandler object at 0x0000000002EE74A8>, <urllib.request.UnknownHandler object at 0x0000000003197B38>, <urllib.request.HTTPHandler object at 0x0000000003197C18>, <urllib.request.HTTPDefaultErrorHandler object at 0x0000000003197CC0>, <urllib.request.HTTPRedirectHandler object at 0x0000000003197BA8>, <urllib.request.FTPHandler object at 0x0000000003197DD8>, <urllib.request.FileHandler object at 0x0000000003197E80>, <urllib.request.HTTPSHandler object at 0x0000000003197E48>, <urllib.request.HTTPErrorProcessor object at 0x0000000003197E10>]
>>> opener.addheaders
[('User-agent', 'Python-urllib/3.3')]
>>> opener.addheaders = [('User-Agent','Test_Proxy_Python3.5_maminyao')]
>>> opener.addheaders
[('User-Agent', 'Test_Proxy_Python3.5_maminyao')]
>>> 

从代理ip列表中随机使用某ip去访问URL的例子

import urllib.request
import random

url = 'http://www.whatismyip.com.tw'
iplist = ['115.32.41.100:80','58.30.231.36:80','123.56.90.175:3128']

proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)})
opener = urllib.request.build_opener(proxy_support)
opener.addheaders = [('User-Agent','Test_Proxy_Python3.5_maminyao')]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')

print(html)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容