Python爬蟲使用代理IP的實現
使用爬蟲時,如果目標網站對訪問的速度或次數要求較高,那麼你的 IP 就很容易被封掉,也就意味著在一段時間內無法再進行下一步的工作。這時候代理 IP 能夠給我們帶來很大的便利,不管網站怎麼封,只要能找到一個新的代理 IP 就可以繼續進行下一步的研究。
目前很多網站都提供了一些免費的代理 IP 供我們使用,當然付費的會更好用一點。本文除了展示怎樣使用代理 IP,也正好體驗一下前面文章中搭建的代理 IP 池,不知道的可以點選這裡:Python搭建代理IP池(一)- 獲取 IP。只要訪問代理池提供的介面就可以獲取到代理 IP 了,接下來就看怎樣使用吧!
測試的網址是:http://httpbin.org/get,訪問該站點可以得到請求的一些相關資訊,其中 origin 欄位就是客戶端的 IP,根據它來判斷代理是否設定成功,也就是是否成功偽裝了IP
獲取 IP
代理池使用 Flask 提供了獲取的介面:http://localhost:5555/random
只要訪問這個介面再返回內容就可以拿到 IP 了
Urllib
先看一下 Urllib 的代理設定方法:
from urllib.error import URLError import urllib.request from urllib.request import ProxyHandler,build_opener # 獲取IP ip_response = urllib.request.urlopen("http://localhost:5555/random") ip = ip_response.read().decode('utf-8') proxy_handler = ProxyHandler({ 'http': 'http://' + ip,'https': 'https://' + ip }) opener = build_opener(proxy_handler) try: response = opener.open('http://httpbin.org/get') print(response.read().decode('utf-8')) except URLError as e: print(e.reason)
執行結果:
{ "args": {},"headers": { "Accept-Encoding": "identity","Host": "httpbin.org","User-Agent": "Python-urllib/3.7" },"origin": "108.61.201.231,108.61.201.231","url": "https://httpbin.org/get" }
Urllib 使用 ProxyHandler 設定代理,引數是字典型別,鍵名為協議型別,鍵值是代理,代理前面需要加上協議,即 http 或 https,當請求的連結是 http 協議的時候,它會呼叫 http 代理,當請求的連結是 https 協議的時候,它會呼叫https代理,所以此處生效的代理是:http://108.61.201.231 和 https://108.61.201.231
ProxyHandler 物件建立之後,再利用 build_opener() 方法傳入該物件來建立一個 Opener,這樣就相當於此 Opener 已經設定好代理了,直接呼叫它的 open() 方法即可使用此代理訪問連結
Requests
Requests 的代理設定只需要傳入 proxies 引數:
import requests # 獲取IP ip_response = requests.get("http://localhost:5555/random") ip = ip_response.text proxies = { 'http': 'http://' + ip,'https': 'https://' + ip,} try: response = requests.get('http://httpbin.org/get',proxies=proxies) print(response.text) except requests.exceptions.ConnectionError as e: print('Error',e.args)
執行結果:
{ "args": {},"headers": { "Accept": "*/*","Accept-Encoding": "gzip,deflate","User-Agent": "python-requests/2.21.0" },"origin": "47.90.28.54,47.90.28.54","url": "https://httpbin.org/get" }
Requests 只需要構造代理字典然後通過 proxies 引數即可設定代理,比較簡單
Selenium
import requests from selenium import webdriver import time # 藉助requests庫獲取IP ip_response = requests.get("http://localhost:5555/random") ip = ip_response.text chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=http://' + ip) browser = webdriver.Chrome(chrome_options=chrome_options) browser.get('http://httpbin.org/get') time.sleep(5)
執行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。