如何加载带参数的起始 URL?

How to load start URLs with parameters?

假设我的开始 URL 分别与一个 ID 配对,例如 (http://www.foo.com, 53453)。有没有办法在给定响应的情况下读取 parse() 中的 id(假设 response.url 是一个开始 URL)?有没有办法给响应自定义 'payload'?我知道我可以进行数据库查找,但我想知道它是否可以在内存中完成。

谢谢

覆盖start_requests() method and yield Request instances passing id inside the meta字典:

class MySpider(Spider):
    def start_requests(self):
        items = get_url_and_ids_from_db()
        for url, id in items:
            yield Request(url, meta={'id': id})

    def parse(self, response):
        id = response.meta['id']
        ...

或者,您可以在 __init__() 中从数据库中获取 url->id 映射,并在 [=20= 中通过 response.url 获取 id ] 方法:

class MySpider(Spider):
    def __init__(self, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)

        self.mapping = get_url_id_mapping_from_db()

        self.start_urls = mapping.keys()

    def parse(self, response):
        id = self.mapping[response.url]
        ...