首页 > 解决方案 > 在python中使用scrapy的LinkExtractor

问题描述

我正在尝试阅读索引页面以从报价站点中抓取报价类别以学习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)

标签: pythonscrapyspyder

解决方案


这是你的错误:

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

你的方法解析在哪里?

改成这样---->

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

推荐阅读