【问题标题】:Get proxy ip address scrapy using to crawl获取代理ip地址scrapy用来爬取
【发布时间】:2015-02-06 12:00:21
【问题描述】:

我使用 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"

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

【问题讨论】:

    标签: python proxy web-scraping scrapy web-crawler


    【解决方案1】:

    您可以发出第一个请求来检查您的公共 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    
    

    【讨论】:

    • 添加另一个用于检查 IP 地址的 url。这不需要解析响应对象,因为正文只包含 IP 地址。 def start_reqests(): yield Request('icanhazip.com', callback=self.check_ip) # 如果需要,在这里从 start_urls 产生其他请求 def check_ip(self, response): print "My public IP is:" + resonse.body
    • @bosnjak 我遵循了您的代码,但刮板永远无法正常工作。原因是您的函数名称包含拼写问题。 start_reqests -> start_requests
    【解决方案2】:

    最快的选择是使用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'}
    

    这样您可以检查中间件是否配置正确以及请求是否通过代理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-13
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2014-09-27
      • 2011-10-11
      • 1970-01-01
      相关资源
      最近更新 更多