scrapy的request的meta参数是什么意思?

meta是一个字典,主要是用解析函数之间传递值,常见的情况是:在parse中给item某些字段提取了值,但是另外一些值需要在parse2中提取,这时候需要将parse中的item传到parse2方法中处理,显然无法直接给parse2设置而外参数。 Request对象接受一个meta参数,一个字典对象,同时Response对象有一个meta属性可以取到相应request传过来的meta。

实例函数如下:
def parse(self, response):
        # 分组提取 方便后序其他元素提取
        name_list = response.xpath('//*[@id="position"]/div[1]/table//tr')[1:-1]
        # print(len(name_list))取

        # 分别取数据
        for li in name_list:
            title = li.xpath('.//a/text()').extract_first()
        # 翻页
        next_href = response.xpath('//*[@id="next"]/@href').extract_first()

        next_url = "https://xxx.com/" + next_href

          yield scrapy.Request(next_url, callback=self.parse2, meta={'url': response.request.url})

    def parse2(self, response):
        url = response.meta['url']
        print(url)

在parse2函数中,用response.meta加上parse中meta的键,即, response.meta['url'],得出结果跟在一个函数中调用一样



猜你喜欢

转载自blog.csdn.net/master_ning/article/details/80558985