首页 > 解决方案 > 我究竟做错了什么 ?我想让我的蜘蛛使用 URL 爬到下一页

问题描述

我是scrapy的新手。我正在研究简单的教程。一切正常,除了我无法爬到下一页。

import scrapy

class QuoteSpider(scrapy.Spider):
    name = "quotes"
    start_urls=['http://quotes.toscrape.com']
    allowed_domains = ["quotes.toscrape.com"]

    def parse(self,response):
        for response in response.xpath('//div[@class="quote"]'):
        yield { 
            "quote":response.xpath('./span[@class="text"]/text()').extract(),
            "author" : response.xpath('./span/small[@class="author"]/text()').extract(),
            "tag" : response.xpath('./div[@class="tags"]/a/text()').extract()
        }
        next_page = response.xpath('//nav/ul[@class="pager"]/li[@class="next"]/a/@href').extract_first()
        if next_page is not None:
            next_page_url = response.urljoin(next_page)
            yield scrapy.Request(url=next_page_url,callback=self.parse)

我的错误信息:

next_page_url = response.urljoin(next_page)

AttributeError:“选择器”对象没有属性“urljoin”

标签: scrapy

解决方案


问题是您正在使用 for 循环覆盖响应对象。因此,for 循环中的内部响应对象只是spidy.language.path_node.PathNode不包含 urljoin 定义的类型。这应该可以解决您的问题。

for response_path in response.xpath('//div[@class="quote"]'):
   yield { 
   "quote":response_path.xpath('./span[@class="text"]/text()').extract(),
        "author" : response_path.xpath('./span/small[@class="author"]/text()').extract(),
        "tag" : response_path.xpath('./div[@class="tags"]/a/text()').extract()
         }
    next_page = response_path.xpath('//nav/ul[@class="pager"]/li[@class="next"]/a/@href').extract_first()
    if next_page is not None:
        next_page_url = response.urljoin(next_page)
        yield scrapy.Request(url=next_page_url,callback=self.parse)

推荐阅读