014-活该你爬虫被封之Scrapy Ip代理中间件

这是坚持技术写做计划(含翻译)的第14篇,定个小目标999,每周最少2篇。python

背景: 房租到期了。
需求: 找到便宜,交通便利的房源,了解当前租房行情,便于砍价。git

在爬取58,赶集,链家,安居客的数据时,被封是常事,基于此,fork并修改了两个库。用于抓取免费代理ip,用于支持爬取租房数据。github

注意:租房网站的数据,大几率失真,仅作参考。docker

其中部分数据截图bash

本文只介绍Scrapy的ip代理中间件,很少讲如何爬取租房网站数据以及数据分析,后边可能会写。dom

获取代理ip

若是有付费的代理ip更好,若是没有的话,能够用我构建的docker镜像scrapy

docker run -p8765:8765 -d anjia0532/ipproxy-dockerfile
复制代码

稍等2-5分钟,访问  http://${docker ip}:8765/ ,若是有值,则抓取代理ip成功。网站

scrapy-proxies-tool

安装

pip install scrapy-proxies-tool
复制代码

配置

修改 Scrapy settings.py,源repo 只支持从文件读取代理ipthis

# Retry many times since proxies often fail
RETRY_TIMES = 10
# Retry on most error codes since proxies fail for different reasons
RETRY_HTTP_CODES = [500, 503, 504, 400, 403, 404, 408]

DOWNLOADER_MIDDLEWARES = {
  'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90,
  'scrapy_proxies.RandomProxy': 100,
  'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
}

PROXY_SETTINGS = {
  # Proxy list containing entries like
  # http://host1:port
  # http://username:password@host2:port
  # http://host3:port
  # ...
  # if PROXY_SETTINGS[from_proxies_server] = True , proxy_list is server address (ref https://github.com/qiyeboy/IPProxyPool and https://github.com/awolfly9/IPProxyTool )
  # Only support http(ref https://github.com/qiyeboy/IPProxyPool#%E5%8F%82%E6%95%B0)
  # list : ['http://localhost:8765?protocol=0'],
  'list':['/path/to/proxy/list.txt'],

  # disable proxy settings and use real ip when all proxies are unusable
  'use_real_when_empty':False,
  'from_proxies_server':False,

  # If proxy mode is 2 uncomment this sentence :
  # 'custom_proxy': "http://host1:port",

  # Proxy mode
  # 0 = Every requests have different proxy
  # 1 = Take only one proxy from the list and assign it to every requests
  # 2 = Put a custom proxy to use in the settings
  'mode':0
}
复制代码

能够经过爬取 myip.ipip.net/ 来判断代理ip是否生效。spa

参考资料

相关文章
相关标签/搜索