代码之家  ›  专栏  ›  技术社区  ›  twitu

使用从列表中获取的URL使用Scrapy进行刮取

  •  1
  • twitu  · 技术社区  · 8 年前
    class PractiseSpider(scrapy.Spider):
        name = "practise"
        allowed_domains = ["practise.com"]
        start_urls = ['https://practise.com/product/{}/']
        def parse(self, response):
            #do something
            #scrape with next url in the list
    

    m product/{}/.format(m[i]) 迭代。 我该怎么做。我应该为每个Url进行新的爬行器调用,还是应该为爬行器编写一些代码来自动迭代列表。如果答案是后者,我该写什么?

    this 但我有一个固定的已知URL列表。

    2 回复  |  直到 8 年前
        1
  •  2
  •   TomáÅ¡ Linhart    8 年前

    如果您事先知道URL,只需填充即可 start_urls m 是一个产品列表(这是我从你写的文章中假设的),那么它看起来是这样的:

    start_urls = ['https://practise.com/product/{}/'.format(product) for product in m]
    
        2
  •  2
  •   Granitosaurus    8 年前

    start_urls ,您可以覆盖 start_requests() 蜘蛛的方法。此方法生成启动爬行器的请求。

    def start_requests(self):
        for url in self.start_urls:
            yield Request(url, dont_filter=True)
    

    因此,您可以在spider中修改此方法,以满足任何需要:

    def start_requests(self):
        ids = pop_ids_from_db()
        for id in ids:
            url = f'http://example.com/product/{id}'
            yield Request(url, dont_filter=True)