當(dāng)我們需要大量的爬取網(wǎng)站信息時(shí),除了切換User-Agent之外,另外一個(gè)重要的方式就是設(shè)置IP代理,以防止我們的爬蟲被拒絕,下面我們就來演示scrapy如何設(shè)置隨機(jī)IPProxy袍祖。
設(shè)置隨機(jī)IPProxy
同樣的你想要設(shè)置IPProxy ,首先需要找到可用的IPProxy 谢揪,通常情況下蕉陋,一些代理網(wǎng)站會提供一些免費(fèi)的ip代理,但是其穩(wěn)定性和可用性很難得到保證拨扶,但是初學(xué)階段凳鬓,只能硬著頭皮去找了,當(dāng)然后期我們可以有其他的方法來尋找可用的IP代理患民,拿到可用的IPProxy 以后缩举,將其添加到settings.py文件中,像下面這樣匹颤,當(dāng)然了仅孩,當(dāng)你看到這篇文章的時(shí)候,他們肯定是已經(jīng)失效了印蓖,你需要自己去找了辽慕。
PROXIES = ['http://183.207.95.27:80', 'http://111.6.100.99:80', 'http://122.72.99.103:80',
'http://106.46.132.2:80', 'http://112.16.4.99:81', 'http://123.58.166.113:9000',
'http://118.178.124.33:3128', 'http://116.62.11.138:3128', 'http://121.42.176.133:3128',
'http://111.13.2.131:80', 'http://111.13.7.117:80', 'http://121.248.112.20:3128',
'http://112.5.56.108:3128', 'http://42.51.26.79:3128', 'http://183.232.65.201:3128',
'http://118.190.14.150:3128', 'http://123.57.221.41:3128', 'http://183.232.65.203:3128',
'http://166.111.77.32:3128', 'http://42.202.130.246:3128', 'http://122.228.25.97:8101',
'http://61.136.163.245:3128', 'http://121.40.23.227:3128', 'http://123.96.6.216:808',
'http://59.61.72.202:8080', 'http://114.141.166.242:80', 'http://61.136.163.246:3128',
'http://60.31.239.166:3128', 'http://114.55.31.115:3128', 'http://202.85.213.220:3128']
而后,在middlewares.py文件中赦肃,添加下面的代碼溅蛉。
import scrapy
from scrapy import signals
import random
class ProxyMiddleware(object):
'''
設(shè)置Proxy
'''
def __init__(self, ip):
self.ip = ip
@classmethod
def from_crawler(cls, crawler):
return cls(ip=crawler.settings.get('PROXIES'))
def process_request(self, request, spider):
ip = random.choice(self.ip)
request.meta['proxy'] = ip
其基本的邏輯和上一篇設(shè)置User-Agent非常類似公浪,因此這個(gè)地方不多贅述。
最后將我們自定義的類添加到下載器中間件設(shè)置中船侧,如下欠气。
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.ProxyMiddleware': 543,
}
測試我們的代理
為了檢測我們的代理是否設(shè)置成功,下面就以一個(gè)例子來進(jìn)行測試镜撩。
我們在spider.py文件中寫入下面的代碼
import scrapy
class Spider(scrapy.Spider):
name = 'ip'
allowed_domains = []
def start_requests(self):
url = 'http://ip.chinaz.com/getip.aspx'
for i in range(4):
yield scrapy.Request(url=url, callback=self.parse, dont_filter=True)
def parse(self,response):
print(response.text)
上面的代碼中预柒,url = 'http://ip.chinaz.com/getip.aspx'
這個(gè)網(wǎng)站可以顯示我們的ip地址,我們用它來測試袁梗,請注意宜鸯,在Request()中,我們必須添加dont_filter=True
因?yàn)槲覀兌啻握埱蟮氖峭粋€(gè)網(wǎng)址围段,scrapy默認(rèn)會把重復(fù)的網(wǎng)址過濾掉。運(yùn)行這個(gè)項(xiàng)目投放,我們可以看到如下的輸出奈泪。