【问题标题】:making request to API from within scrapy function从 scrapy 函数中向 API 发出请求
【发布时间】:2016-09-10 20:48:29
【问题描述】:

我正在使用scrapy。我想根据每个请求轮换代理,并从我拥有的返回单个代理的 api 获取代理。我的计划是向api发出请求,获取代理,然后使用它来设置代理:

http://stackoverflow.com/questions/4710483/scrapy-and-proxies 

我将在哪里分配它:

request.meta['proxy'] = 'your.proxy.address'; 

我有以下几点:

class ContactSpider(Spider):
    name = "contact"

def parse(self, response):

    for i in range(1,3,1):
        PR= Request('htp//myproxyapi.com',  headers= self.headers)
        newrequest= Request('htp//sitetoscrape.com',  headers= self.headers)
        newrequest.meta['proxy'] = PR 

但我不确定如何使用 Scrapy Request 对象来执行 api 调用。调试时我没有收到对 PR 请求的响应。我需要在单独的函数中执行此操作并使用 yield 语句还是我的方法错误?

【问题讨论】:

    标签: proxy scrapy


    【解决方案1】:

    我需要在单独的函数中执行此操作并使用 yield 语句还是我的方法错误?

    是的。 Scrapy 使用回调模型。您需要:

    1. PR 对象返回给scrapy 引擎。
    2. 解析 PR 的响应,并在其回调中,yield newrequest

    一个简单的例子:

    def parse(self, response):
        for i in range(1,3,1):
            PR = Request(
                'http://myproxyapi.com', 
                headers=self.headers,
                meta={'newrequest': Request('htp//sitetoscrape.com',  headers=self.headers),},
                callback=self.parse_PR
            )
            yield PR
    
    def parse_PR(self, response):
        newrequest = response.meta['newrequest']
        proxy_data = get_data_from_response(PR)
        newrequest.meta['proxy'] = proxy_data
        yield newrequest
    

    另请参阅:http://doc.scrapy.org/en/latest/topics/request-response.html#topics-request-response-ref-request-callback-arguments

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 2019-08-10
      • 2019-11-23
      • 2022-10-06
      相关资源
      最近更新 更多