python爬蟲框架scrapy代理中間件掌握學(xué)習(xí)教程
代理的使用場(chǎng)景
編寫爬蟲代碼的程序員,永遠(yuǎn)繞不開(kāi)就是使用代理,在編碼過(guò)程中,你會(huì)碰到如下情形:
網(wǎng)絡(luò)不好,需要代理;
目標(biāo)站點(diǎn)國(guó)內(nèi)訪問(wèn)不了,需要代理;
網(wǎng)站封殺了你的 IP,需要代理。
使用 HttpProxyMiddleware 中間件
本次的測(cè)試站點(diǎn)依舊使用 http://httpbin.org/
,通過(guò)訪問(wèn) http://httpbin.org/ip可以獲取當(dāng)前請(qǐng)求的 IP 地址。
HttpProxyMiddleware 中間件默認(rèn)是開(kāi)啟的,可以查看其源碼重點(diǎn)為 process_request()
方法。
修改代理的方式非常簡(jiǎn)單,只需要在 Requests
請(qǐng)求創(chuàng)建的時(shí)候,增加 meta
參數(shù)即可。
import scrapy class PtSpider(scrapy.Spider): name = 'pt' allowed_domains = ['httpbin.org'] start_urls = ['http://httpbin.org/ip'] def start_requests(self): yield scrapy.Request(url=self.start_urls[0], meta={'proxy': 'http://202.5.116.49:8080'}) def parse(self, response): print(response.text)
接下來(lái)通過(guò)獲取一下 https://www.kuaidaili.com/free/
網(wǎng)站的代理 IP,并測(cè)試其代理是否可用。
import scrapy class PtSpider(scrapy.Spider): name = 'pt' allowed_domains = ['httpbin.org', 'kuaidaili.com'] start_urls = ['https://www.kuaidaili.com/free/'] def parse(self, response): IP = response.xpath('//td[@data-title="IP"]/text()').getall() PORT = response.xpath('//td[@data-title="PORT"]/text()').getall() url = 'http://httpbin.org/ip' for ip, port in zip(IP, PORT): proxy = f"http://{ip}:{port}" meta = { 'proxy': proxy, 'dont_retry': True, 'download_timeout': 10, } yield scrapy.Request(url=url, callback=self.check_proxy, meta=meta, dont_filter=True) def check_proxy(self, response): print(response.text)
接下來(lái)將可用的代理 IP 保存到 JSON 文件中。
import scrapy class PtSpider(scrapy.Spider): name = 'pt' allowed_domains = ['httpbin.org', 'kuaidaili.com'] start_urls = ['https://www.kuaidaili.com/free/'] def parse(self, response): IP = response.xpath('//td[@data-title="IP"]/text()').getall() PORT = response.xpath('//td[@data-title="PORT"]/text()').getall() url = 'http://httpbin.org/ip' for ip, port in zip(IP, PORT): proxy = f"http://{ip}:{port}" meta = { 'proxy': proxy, 'dont_retry': True, 'download_timeout': 10, '_proxy': proxy } yield scrapy.Request(url=url, callback=self.check_proxy, meta=meta, dont_filter=True) def check_proxy(self, response): proxy_ip = response.json()['origin'] if proxy_ip is not None: yield { 'proxy': response.meta['_proxy'] }
同時(shí)修改 start_requests
方法,獲取 10 頁(yè)代理。
class PtSpider(scrapy.Spider): name = 'pt' allowed_domains = ['httpbin.org', 'kuaidaili.com'] url_format = 'https://www.kuaidaili.com/free/inha/{}/' def start_requests(self): for page in range(1, 11): yield scrapy.Request(url=self.url_format.format(page))
實(shí)現(xiàn)一個(gè)自定義的代理中間件也比較容易,有兩種辦法,第一種繼承 HttpProxyMiddleware
,編寫如下代碼:
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware from collections import defaultdict import random class RandomProxyMiddleware(HttpProxyMiddleware): def __init__(self, auth_encoding='latin-1'): self.auth_encoding = auth_encoding self.proxies = defaultdict(list) with open('./proxy.csv') as f: proxy_list = f.readlines() for proxy in proxy_list: scheme = 'http' url = proxy.strip() self.proxies[scheme].append(self._get_proxy(url, scheme)) def _set_proxy(self, request, scheme): creds, proxy = random.choice(self.proxies[scheme]) request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = b'Basic ' + creds
代碼核心重寫了 __init__
構(gòu)造方法,并重寫了 _set_proxy
方法,在其中實(shí)現(xiàn)了隨機(jī)代理獲取。
同步修改 settings.py
文件中的代碼。
DOWNLOADER_MIDDLEWARES = { 'proxy_text.middlewares.RandomProxyMiddleware': 543, }
創(chuàng)建一個(gè)新的代理中間件類
class NRandomProxyMiddleware(object): def __init__(self, settings): # 從settings中讀取代理配置 PROXIES self.proxies = settings.getlist("PROXIES") def process_request(self, request, spider): request.meta["proxy"] = random.choice(self.proxies) @classmethod def from_crawler(cls, crawler): if not crawler.settings.getbool("HTTPPROXY_ENABLED"): raise NotConfigured return cls(crawler.settings)
可以看到該類從 settings.py
文件中的 PROXIES
讀取配置,所以修改對(duì)應(yīng)配置如下所示:
DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': None, 'proxy_text.middlewares.NRandomProxyMiddleware': 543, } # 代碼是前文代碼采集的結(jié)果 PROXIES = ['http://140.249.48.241:6969', 'http://47.96.16.149:80', 'http://140.249.48.241:6969', 'http://47.100.14.22:9006', 'http://47.100.14.22:9006']
如果你想測(cè)試爬蟲,可編寫一個(gè)隨機(jī)返回請(qǐng)求代理的函數(shù),將其用到任意爬蟲代碼之上,完成本博客任務(wù)。
以上就是python爬蟲框架scrapy代理中間件掌握學(xué)習(xí)教程的詳細(xì)內(nèi)容,更多關(guān)于scrapy框架代理中間件學(xué)習(xí)的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。