如何将 scrapy 与自动旋转代理一起使用?

How to use scrapy with auto-rotating proxy?

我有一个从 storm proxies 获得的自动旋转代理,但我不知道如何将它与 scrapy 一起正确使用。对于我发出的所有请求,IP 保持不变。 storm proxies 的支持说需要关闭当前连接才能更改IP。

但是我不知道如何关闭连接或者每次都创建一个新的请求或者有什么其他的方法吗?

这是我当前的代码。

import scrapy
import scraper_helper

class EbayfastSpider(scrapy.Spider):
    name = 'test'
    custom_settings = {
        'CONCURRENT_REQUESTS': 10,
        'CONCURRENT_REQUESTS_PER_IP' : 1
        }

    header_string = """
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
    x-requested-with: XMLHttpRequest
    """
    headers = scraper_helper.get_dict(header_string)

    def start_requests(self):
        url='https://httpbin.org/ip'
        for index in range(10):
            yield scrapy.Request(url=url, callback=self.parse,headers= self.headers, dont_filter=True,
                meta={'proxy': 'rotating_proxy'}
                )
            print(index)            
    
    def parse(self,response):
        print(response.text)

您可以通过在请求 header 中添加 Connection: close 来表示关闭当前连接。这意味着连接将在响应后关闭。它还会因为重复 TCP 3 次握手而导致抓取延迟。