使用 Urllib 和 Scrapy 进行分页

Using Urllib with Scrapy for Pagination

尝试使用 Scrapy 抓取下一页,Python 3.5 使用 urlib python 库

    import datetime
    import urllib.request
    import urllib.error
    import urllib.parse
    import socket
    import scrapy
    from scrapy.loader.processors import MapCompose, Join
    from scrapy.loader import ItemLoader
    from properties.items import PropertiesItem


    class BasicSpider(scrapy.Spider):
        name = "manual"
        allowed_domains = ["web"]

        # Start on the first index page
        start_urls = (
            'http://scrapybook.s3.amazonaws.com/properties/index_00000.html',
        )

        def parse(self, response):
            # Get the next index URLs and yield Requests
            next_selector = response.xpath('//*[contains(@class,"next")]//@href')
            for url in next_selector.extract():
                yield Request(urllib.parse.urljoin(response.url, url))

            # Get item URLs and yield Requests
            item_selector = response.xpath('//*[@itemprop="url"]/@href')
            for url in item_selector.extract():
                yield Request(urllib.parse.urljoin(response.url, url), callback=self.parse_item)


        def parse(self, response):
            l = ItemLoader(item=PropertiesItem(), response=response)
            l.add_xpath('title', '//*[@itemprop="name"]/text()')
            return l.load_item()

一切正常,没有错误,但 Scrapy 仅获取第一页,但根据代码,它应该获取所有下一页

这是输出

[{
    "title": [
      "bermondsey ec kennington drive acton seven rm",
    .......
      "mary conversion borders eastham with gas"
  }]

// Only Page 0 Titles :(

请求或 Urllib 调用语法有问题吗?

PS : Xpath 工作,Scrapy Shell 'URL'

您似乎有两个 parse 功能。所以你只有第二个,因为它覆盖了第一个。

只需将第二个重命名为 parse_item,就像您的其余代码似乎表明的那样。

让我们从 Python 包的错误使用开始

  1. 使用 Request 而不导入它,修复它。

    来自 scrapy 导入请求

  2. 错误使用urljoin class from urllib,先导入

    从urllib.parse导入url加入

    现在直接使用 urljoin 而无需调用 urllib.parse.urljoin

    更改它

    yield 请求(urllib.parse.urljoin(response.url, url)) yield Request(urllib.parse.urljoin(response.url, url), callback=self.parse_item)

  3. 不调用 parse_item

    上调用它

    def parse(self, response): #replace parse to parse_item

PS :如果此代码来自 Learning Scrapy Book 那么这里是完整的 git python3 版本 [=14] 的示例=]

https://github.com/Rahulsharma0810/Scrapy-Pagination-URLJOIN-Example