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的例子
1 import urllib.request 2 import random 3 4 url = 'http://www.whatismyip.com.tw' 5 iplist = ['115.32.41.100:80','58.30.231.36:80','123.56.90.175:3128'] 6 7 proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)}) 8 opener = urllib.request.build_opener(proxy_support) 9 opener.addheaders = [('User-Agent','Test_Proxy_Python3.5_maminyao')] 10 urllib.request.install_opener(opener) 11 response = urllib.request.urlopen(url) 12 html = response.read().decode('utf-8') 13 14 print(html)