使用代理ip地址scrapy进行爬网

cyn*_*yn0 4 python proxy web-crawler scrapy web-scraping

我使用Tor来抓取网页.我开始了tor和polipo服务并添加了

class ProxyMiddleware(object):   # overwrite process request   def
  process_request(self, request, spider):
     # Set the location of the proxy
    request.meta['proxy'] = "127.0.0.1:8123"
Run Code Online (Sandbox Code Playgroud)

现在,我如何确保scrapy对请求使用不同的IP地址?

bos*_*jak 13

您可以产生第一个检查公共IP的请求,并将其与您在不使用Tor/VPN的情况下访问http://checkip.dyndns.org/时看到的IP进行比较.如果它们不相同,scrapy正在使用不同的IP.

def start_reqests():
    yield Request('http://checkip.dyndns.org/', callback=self.check_ip)
    # yield other requests from start_urls here if needed

def check_ip(self, response):
    pub_ip = response.xpath('//body/text()').re('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')[0]
    print "My public IP is: " + pub_ip

    # yield other requests here if needed    
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 8

最快的选择是使用scrapy shell和检查meta包含proxy.

从项目根目录启动它:

$ scrapy shell http://google.com
>>> request.meta
{'handle_httpstatus_all': True, 'redirect_ttl': 20, 'download_timeout': 180, 'proxy': 'http://127.0.0.1:8123', 'download_latency': 0.4804518222808838, 'download_slot': 'google.com'}
>>> response.meta
{'download_timeout': 180, 'handle_httpstatus_all': True, 'redirect_ttl': 18, 'redirect_times': 2, 'redirect_urls': ['http://google.com', 'http://www.google.com/'], 'depth': 0, 'proxy': 'http://127.0.0.1:8123', 'download_latency': 1.5814828872680664, 'download_slot': 'google.com'}
Run Code Online (Sandbox Code Playgroud)

这样您就可以检查中间件是否配置正确并且请求是通过代理进行的.