是否可以为每个单独的请求将变量从 start_requests() 传递到 parse()? [英] Is it possible to pass a variable from start_requests() to parse() for each individual request?

查看:27
本文介绍了是否可以为每个单独的请求将变量从 start_requests() 传递到 parse()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用循环在 start_request() 中生成我的请求,我想将索引传递给 parse() 以便它可以将它存储在项目.但是,当我使用 self.i 时,输出具有每个项目的 i 最大值(最后一圈).我可以使用 response.url.re('regex to extract the index') 但我想知道是否有一种干净的方法可以将变量从 start_requests 传递到解析.

I'm using a loop to generate my requests inside start_request() and I'd like to pass the index to parse() so it can store it in the item. However when I use self.i the output has the i max value (last loop turn) for every items. I can use response.url.re('regex to extract the index') but I wonder if there is a clean way to pass a variable from start_requests to parse.

推荐答案

你可以使用 scrapy.Request meta 属性:

You can use scrapy.Request meta attribute:

import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'

    def start_requests(self):
        urls = [...]
        for index, url in enumerate(urls):
            yield scrapy.Request(url, meta={'index':index})

    def parse(self, response):
        print(response.url)
        print(response.meta['index'])

这篇关于是否可以为每个单独的请求将变量从 start_requests() 传递到 parse()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆