python - Scrapy:从分页中抓取数据

标签 python xpath web-scraping scrapy

到目前为止,我已经从一页中抓取了数据。我想继续直到分页结束。

Click Here查看页面

似乎有问题,因为 href 包含一个 javascript 元素。

<a href="javascript:void(0)" class="next" data-role="next" data-spm-anchor-id="a2700.galleryofferlist.pagination.8">Next</a>

我的代码

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


class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

def parse(self, response):
    for products in response.xpath('//div[contains(@class, "m-gallery-product-item-wrap")]'):
        item = {
            'product_name': products.xpath('.//h2/a/@title').extract_first(),
            'price': products.xpath('.//div[@class="price"]/b/text()').extract_first('').strip(),
            'min_order': products.xpath('.//div[@class="min-order"]/b/text()').extract_first(),
            'company_name': products.xpath('.//div[@class="stitle util-ellipsis"]/a/@title').extract_first(),
            'prod_detail_link': products.xpath('.//div[@class="item-img-inner"]/a/@href').extract_first(),
            'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first('').strip(),
            #'image_url': products.xpath('.//div[@class=""]/').extract_first(),
         }
        yield item

    #Follow the paginatin link
    next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()
    if next_page_url:
        yield scrapy.Request(url=next_page_url, callback=self.parse)

问题

  • 如何解决分页问题?

你能帮上什么忙

  • 帮我修改代码,使我可以跟随分页链接并抓取数据直到最后。

最佳答案

您可以使用类似的代码获取下一页 URL:

next_page_url = response.xpath('//div[@class="ui2-pagination-pages"]/span[@class="current"]/following-sibling::a[1][contains(@href, "?page=")]/@href').extract_first()

但这行不通,因为分页 block 是由 Javascript 呈现的:-(

但是你可以使用一些技巧:

next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()

关于python - Scrapy:从分页中抓取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241118/

相关文章:

python - numpy:以相反的顺序引用元素

python - 如何从应用程序本身重新启动 python 应用程序

xpath - 在 cucumber 测试中检查链接的正确方法是什么?

Python xpath解析返回内存定位

python - 如何使用 Reddit API 获取超过 1000 张图片?

python - 如何从使用 react.js 和 Python 中的 Selenium 的网页中抓取数据?

python - 使用 Python 自动调整 Excel 工作表的所有列

ruby-on-rails - Xpath 2.0 - xmlXPathCompOpEval : function matches not found

xml - 查找同级 dateTime 节点的最小值/最大值的最短 XPath

python - Arduino 和 Python 通信错误