在 python 中使用 scrapy 的 LinkExtractor

LinkExtractor using scrapy in python

我正在尝试阅读索引页面以从报价网站上抓取报价类别以学习 scrapy。我是新手!

我可以用我的代码阅读单个页面(类别),但是我想阅读索引页面来阅读报价页面。

def parse_item 部分适用于单个页面。但是我无法获得 LinkExtractor 部分来推断链接。

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    allowed_domains = ['website.com']
    start_urls = [
        'https://www.website.com/topics'
    ]

    rules = (
        Rule(LinkExtractor(allow=('^\/topics.*', )), callback='parse_item')  
    )


    def parse_item(self, response):
        for quote in response.css('#quotesList .grid-item'):                                       
           yield {
              'text': quote.css('a.oncl_q::text').extract_first(),
              'author': quote.css('a.oncl_a::text').extract_first(),
              'tags': quote.css('.kw-box a.oncl_list_kc::text').extract(),
              'category' : response.css('title::text').re(r'(\w+).*')  
            }

        next_page = response.css('div.bq_s.hideInfScroll > nav > ul > li:nth-last-child(1) a::attr(href)').extract_first()
        if next_page is not None:
          next_page = response.urljoin(next_page)
          yield scrapy.Request(next_page, callback=self.parse)

这是你的错误:

yield scrapy.Request(next_page, callback=self.parse)

你的方法在哪里解析?

这样改---->

 yield scrapy.follow(url=next_page, callback=self.parse_item)

我已经解决了这个问题。虽然 Rule(LinkExtractor 可能有解决此问题的方法,但我改为使用 response.css 级联查询来跟踪主题页面上的链接。

这是最终的工作版本...

import scrapy

class QuotesBrainy(scrapy.Spider):
    name = 'Quotes'

start_urls = ['https://www.website.com/topics/']

def parse(self, response):
    # follow links to topic pages
    for href in response.css('a.topicIndexChicklet::attr(href)'):
        yield response.follow(href, self.parse_item)


def parse_item(self, response):
    # iterate through all quotes
    for quote in response.css('#quotesList .grid-item'):                                       
       yield {
          'text': quote.css('a.oncl_q::text').extract_first(),
          'author': quote.css('a.oncl_a::text').extract_first(),
          'tags': quote.css('.kw-box a.oncl_list_kc::text').extract(),
          'category' : response.css('title::text').re(r'(\w+).*')  
        }

    # go through the pagination links to access infinite scroll           
    next_page = response.css('div.bq_s.hideInfScroll > nav > ul > li:nth-last-child(1) a::attr(href)').extract_first()
    if next_page is not None:
      next_page = response.urljoin(next_page)
      yield scrapy.Request(next_page, callback=self.parse_item)