Scrapy:从分页中抓取数据 [英] Scrapy: scraping data from Pagination

查看:38
本文介绍了Scrapy:从分页中抓取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

so far I have scraped data from one page. I want to continue until the end of the pagination.

点击此处查看页面

Click Here to view the page

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

There seems to be a problem because the href contains a javascript element.

<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)

问题

  • 如何解决分页问题?
    • 帮助我修改代码,以便我可以按照分页链接并抓取数据直到最后.

    推荐答案

    可以使用类似的代码获取下一页的网址:

    You can use similar code to get next page URL:

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

    但这不起作用,因为分页块是由 Javascript 呈现的 :-(

    but this will not work because pagination block is rendered by Javascript :-(

    但是你可以使用某种技巧:

    But you can use some kind of trick:

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

    这篇关于Scrapy:从分页中抓取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆