【问题标题】:How I can take data from all pages?如何从所有页面获取数据?
【发布时间】:2020-02-13 10:26:34
【问题描述】:

这是我第一次在 python 中使用 Scrapy 框架。

所以我编写了这段代码。

# -*- coding: utf-8 -*-
import scrapy


class SpiderSpider(scrapy.Spider):
    name = 'spider'
    start_urls = [
        'https://www.emag.ro/televizoare/c'
    ]

    def parse(self, response):
        for i in response.xpath('//div[@class="card-section-wrapper js-section-wrapper"]'):
            yield {
                'product-name': i.xpath('.//a[@class="product-title js-product-url"]/text()')
                                .extract_first().replace('\n','')
            }

        next_page_url = response.xpath('//a[@class="js-change-page"]/@href').extract_first()
        if next_page_url is not None:
            yield scrapy.Request(response.urljoin(next_page_url))

当我查看该网站时,它有超过 800 种产品。但我的脚本只占用了前 2 页近 200 种产品...

我尝试使用 css 选择器和 xpath,都是相同的错误。

谁能找出问题出在哪里?

谢谢!

【问题讨论】:

    标签: python scrapy frameworks


    【解决方案1】:

    您尝试抓取的网站正在从 API 获取数据。当您点击分页链接时,它会向 API 发送 ajax 请求以获取更多产品并在页面上显示它们。

    自从

    Scrapy 不模拟浏览器环境本身。

    所以一种方法是你

    1. 在浏览器网络选项卡中分析请求以检查端点和参数

    2. 自己在 scrapy 中构建类似的请求

    3. 使用适当的参数调用该端点以从 API 获取产品。

    您还需要从从 API 获得的 json 响应中提取下一页。通常有一个名为 pagination 的键,其中包含与总页数、下一页等相关的信息。

    【讨论】:

      【解决方案2】:

      我终于想通了。

      # -*- coding: utf-8 -*-
      import scrapy
      from ..items import ScraperItem
      
      
      class SpiderSpider(scrapy.Spider):
          name = 'spider'
          page_number = 2
          start_urls = [
              'https://www.emag.ro/televizoare/c'
          ]
      
          def parse(self, response):
      
              items = ScraperItem()
      
              for i in response.xpath('//div[@class="card-section-wrapper js-section-wrapper"]'):
      
                  product_name = i.xpath('.//a[@class="product-title js-product-url"]/text()').extract_first().replace('\n                        ','').replace('\n                    ','')
      
                  items["product_name"] = product_name
      
                  yield items
      
                  next_page = 'https://www.emag.ro/televizoare/p' + str(SpiderSpider.page_number) + '/c'
      
                  if SpiderSpider.page_number <= 28:
                      SpiderSpider.page_number += 1
                      yield response.follow(next_page, callback = self.parse)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 2015-12-02
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        相关资源
        最近更新 更多