python使用代理訪問伺服器

來源:互聯網
上載者:User

標籤:opener   pen   gen   urlopen   handler   連接埠號碼   使用   http重新導向   headers   

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)

 

python使用代理訪問伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.