【问题标题】:How to scrape multiple URLs with same parse using Scrapy?如何使用 Scrapy 抓取具有相同解析的多个 URL?
【发布时间】:2019-05-14 14:21:58
【问题描述】:

您好,我的蜘蛛脚本有问题,我想让我的脚本尽可能可读,并且我想尽可能多地保存代码。是否可以在不同的 URL 上使用相同的解析?

我只想每页抓取 10 个项目并将其保存在 items.py 中的不同项目功能上

这是我的代码

def start_requests(self):  #I have 3 URL's Here
    yield scrapy.Request('https://teslamotorsclub.com/tmc/post-ratings/6/posts', self.parse) #Url 1
    yield scrapy.Request('https://teslamotorsclub.com/tmc/post-ratings/7/posts', self.parse) #Url 2
    yield scrapy.Request('https://teslamotorsclub.com/tmc/post-ratings/1/posts', self.parse) #Url 3


def parse(self, response): #My logic is something like this    
    if Url == Url1:
        item = TmcnfSpiderItem()
    elif Url == Url2:
        item = TmcnfSpiderItem2()
    elif Url == Url3:
        item = TmcnfSpiderItem3()

    if count <= 9:
        count += 1
        info = response.css("[id^='fc-post-" + postno_only +"']")
        author = info.xpath("@data-author").extract_first()
        item['author'] = author      
        yield item
     else:
         #Move to next URL and perform same parse

有什么想法吗?

【问题讨论】:

    标签: web-scraping scrapy scrape


    【解决方案1】:

    我认为你可以尝试从start_requests 传递所有数据,就像这里:

    def start_requests(self):
        urls = (
            ('https://teslamotorsclub.com/tmc/post-ratings/6/posts', TmcnfSpiderItem),
            ('https://teslamotorsclub.com/tmc/post-ratings/7/posts', TmcnfSpiderItem2),
            ('https://teslamotorsclub.com/tmc/post-ratings/1/posts', TmcnfSpiderItem3),
        )
        for url, itemclass in urls:
            yield scrapy.Request(url, meta={'itemclass': itemclass}) 
    
    def parse(self, response):
        item = response.meta['itemclass']()
    

    因此,您为每个 url 传递您的项目类名,并在 parse 函数中创建此类的新元素。

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2018-02-06
      • 1970-01-01
      • 2015-07-05
      • 2013-02-17
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多