码迷,mamicode.com
首页 > 编程语言 > 详细

python使用代理访问服务器

时间:2017-04-11 11:03:33      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:alt   print   就会   int   com   err   unknown   python使用   director   

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)
技术分享

 

原网址:http://www.cnblogs.com/paomaliuju/p/5176461.html

python使用代理访问服务器

标签:alt   print   就会   int   com   err   unknown   python使用   director   

原文地址:http://www.cnblogs.com/jmmchina/p/6692576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!