配置scrapy的动态User-Agent和IP代理以及验证码的识别
User-Agent
在scrapy的settings里写入以下代码即可配置动态User-Agent
# 配置动态的user agent from fake_useragent import UserAgent ua = UserAgent() USER_AGENT = ua.random
IP代理
想要设置IPProxy ,首先需要找到可用的IPProxy ,通常情况下,一些代理网站会提供一些免费的ip代理,但是其稳定性和可用性很难得到保证,但是初学阶段,只能硬着头皮去找了,当然后期我们可以有其他的方法来寻找可用的IP代理。下面是自动爬取免费的IP代码:
import time import requests # 爬取免费IP def crawl_ips(): from scrapy.selector import Selector headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17'} for i in range(1, 100): url = "https://www.kuaidaili.com/free/inha/{}/".format(i) print(url) res = requests.get(url=url, headers=headers) print(res.status_code) Sel = Selector(text=res.text) ips = Sel.xpath('//td[@data-title="IP"]/text()').extract() print('第{}页IP:'.format(i)) print(ips) time.sleep(1) if __name__ == '__main__': crawl_ips()
拿到可用的IPProxy 以后,将其添加到settings.py文件中。
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):
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
其基本的逻辑和上一篇设置User-Agent非常类似,因此这个地方不多赘述。
最后将我们自定义的类添加到下载器中间件设置中,如下。
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.ProxyMiddleware': 543,
}
scrapy的官网也给我们提供了一个收费的库scrpay-crawlera,它很方便的可以配置动态的IP代理,但是需要收费。
另外一个工具叫做Tor,这是一个洋葱浏览器,洋葱网络,访问网络时进行多次包装,让爬取得网站无法识别。但需要vpn下载。安全和稳定性甚至高于收费的IP代理。
验证码识别
编码实现:验证码识别可以进行编码方式识别,但不建议这样实现,因为耗时且准确率很低。
在线打码:通过API进行验证码识别,成本低且正确率较高。
人工打码:正确率最高,但价格最贵。
现在只对在线打码平台进行说明-云打码


浙公网安备 33010602011771号