python使用代理ip


python使用代理的方法有兩種

1.

 1 #先創建代理ip對象
 2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
 3 
 4 #定制一個opener對象
 5 opener = urllib.request.build_opener(proxy_support)
 6 
 7 #安裝這個opener對象,以后的urlopen就一直使用這個代理地址了
 8 urllib.request.install_opener(opener)
 9 
10 #發出請求時,就是用到這個代理地址了
11 html = urllib.request.urlopen('xxxxxxxxxx').read()

2.

1 #先創建代理ip對象
2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
3 
4 #定制一個opener對象
5 opener = urllib.request.build_opener(proxy_support)
6 
7 #這里可以直接使用opener對象發出請求
8 html = opener.open('xxxxxxxxx').read() 

示例代碼:

 1 import urllib.request
 2 
 3 #這一段三句話是為了請求時帶上瀏覽器標識,因為有的網站看到是爬蟲的標識直接返回403
 4 #請求的網站不涉及到提交數據,所以沒有給出data參數
 5 url = 'https://whatismyipaddress.com/'
 6 header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
 7 req = urllib.request.Request(url,headers=header)
 8 
 9 #使用代理和還原不使用代理的方法
10 #if語句相當於一個開關,不要寫成True
11 use_proxy = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
12 null_proxy = urllib.request.ProxyHandler()
13 if True:
14     opener = urllib.request.build_opener(use_proxy)
15 else:
16     opener = urllib.request.build_opener(null_proxy)
17 #根據上面的開關,安裝的opener對象是否帶有代理地址
18 urllib.request.install_opener(opener)
19 
20 #獲取返回結果
21 #同時可以使用html = opener.open(req).read()獲取結果
22 html = urllib.request.urlopen(req).read()
23 
24 #這網頁返回頁面的內容太多,在控制台不好查看,
25 #並且返回的內容是二進制格式,可以直接寫入文件,當個網頁查看
26 with open('E:\\whatismyip.html','wb') as file:
27     file.write(html)
28     print('OK')

 

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM