首页 > 解决方案 > 响应在 Scrapy Shell 中有效,但在代码中无效

问题描述

我是 Scrapy 的新手。我为这个网站写了我的第一个蜘蛛https://book24.ru/knigi-bestsellery/?section_id=1592它工作正常

import scrapy
 
class BookSpider(scrapy.Spider):
 name = 'book24'
 start_urls = ['https://book24.ru/knigi-bestsellery/']
 
  def parse(self, response):
  
     for link in response.css('div.product-card__image-holder a::attr(href)'):
       yield response.follow(link, callback=self.parse_book)
    
     for i in range (1, 5):
       next_page = f'https://book24.ru/knigi-bestsellery/page-{i}/'
       yield response.follow(next_page, callback=self.parse)
       print(i)
      
 def parse_book(self, response):
   yield{
         'name': response.css('h1.product-detail-page__title::text').get(),
         'type': response.css('div.product-characteristic__value a::attr(title)')[2].get()
           }

现在我尝试只为一页编写蜘蛛

import scrapy
 
class BookSpider(scrapy.Spider):
 name = 'book'
 start_urls = ['https://book24.ru/product/transhumanism-inc-6015821/']
 

 def parse_book(self, response):
   yield{
         'name': response.css('h1.product-detail-page__title::text').get(),
         'type': response.css('div.product-characteristic__value a::attr(title)')[2].get()
           }

而且它不起作用,我在终端中执行此命令后得到一个空文件。

scrapy crawl book -O book.csv

我不知道为什么。将不胜感激!

标签: scrapyweb-crawlerscrapy-shell

解决方案


你得到了加薪

NotImplementedError(f'{self.__class__.__name__}.parse callback is not defined')
NotImplementedError: BookSpider.parse callback is not defined

根据文件

parse():将调用的方法来处理为每个请求下载的响应。response 参数是 TextResponse 的一个实例,它保存页面内容并具有更多有用的方法来处理它。

parse() 方法通常解析响应,将抓取的数据提取为 dicts,并找到要遵循的新 URL 并从中创建新请求 (Request)。

只需重命名您 def parse_book(self, response): to def parse(self, response): 的工作即可。


推荐阅读