【问题标题】:Scrapy Spider only pulling the first value from item containerScrapy Spider 仅从项目容器中提取第一个值
【发布时间】:2022-01-24 19:03:18
【问题描述】:

我正在尝试收集漫画书的定价信息。我最终得到的是一个蜘蛛,它遍历顶部 css 选择器的所有实例,然后仅从包含我所追求的定价信息的选择器的第一个实例返回所需的值。

我的最终目标是能够创建一个管道来为 SQLite 数据库提供标题、sku、价格和实际列表的 url。这是我的代码:

class XmenscrapeSpider(scrapy.Spider):
name = 'finalscrape'
allowed_domains = ['mycomicshop.com']
start_urls = ['https://www.mycomicshop.com/search?TID=222421']

def parse(self, response):
    for item in response.css('td.highlighted'):
        yield {
            'title' : response.xpath('.//meta[@itemprop="sku"]/@content').get()
            }
    
    
    next_page = response.css('li.next a::attr(href)').extract()[1]
    if next_page is not None:
        yield resonse.follow(next_page, callback- self.parse)

我的输出如下所示:

   {'title': '100 Bullets (1999 DC Vertigo) 1 CGC 9.8'}
    2022-01-24 13:53:04 [scrapy.core.scraper] DEBUG: Scraped from <200 
    https://www.mycomicshop.com/search?TID=222421>
    {'title': '100 Bullets (1999 DC Vertigo) 1 CGC 9.8'}
    2022-01-24 13:53:04 [scrapy.core.scraper] DEBUG: Scraped from <200 
    https://www.mycomicshop.com/search?TID=222421>
    {'title': '100 Bullets (1999 DC Vertigo) 1 CGC 9.8'}
    2022-01-24 13:53:04 [scrapy.core.scraper] DEBUG: Scraped from <200 
    https://www.mycomicshop.com/search?TID=222421>
    {'title': '100 Bullets (1999 DC Vertigo) 1 CGC 9.8'}
    2022-01-24 13:53:04 [scrapy.core.scraper] DEBUG: Scraped from <200 
    https://www.mycomicshop.com/search?TID=222421>
    {'title': '100 Bullets (1999 DC Vertigo) 1 CGC 9.8'}

如果您查看我试图抓取的 URL,您会发现我只从第一个标记中获得了所需的值,尽管蜘蛛在页面上遍历了它的五个实例。我觉得这是一个简单的解决方案,但我到此为止。关于什么可能是一个简单的解决方法的任何想法?

【问题讨论】:

    标签: python css xpath scrapy


    【解决方案1】:

    您需要使用相对 xpath 到 item

    import scrapy
    
    
    class XmenscrapeSpider(scrapy.Spider):
        name = 'finalscrape'
        allowed_domains = ['mycomicshop.com']
        start_urls = ['https://www.mycomicshop.com/search?TID=222421']
    
        def parse(self, response):
            for item in response.css('td.highlighted'):
                yield {
                    # 'title': response.xpath('.//meta[@itemprop="sku"]/@content').get()
                    'title': item.xpath('.//meta[@itemprop="name"]/@content').get()
                }
    
            next_page = response.css('li.next a::attr(href)').get()
            if next_page:
                yield response.follow(next_page, callback=self.parse)
    

    注意:您只会遍历突出显示的项目,并且由于下一页没有任何内容,因此您不会从中得到任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多