(xPathHelp) Scrapy 不会跳转到下一页,只会抓取第一页

时间:2021-01-14 08:38:21

标签: python-3.x web-scraping xpath scrapy scrapy-shell

我正在尝试提取 href Here 中的嵌套 url,以便我可以为我的蜘蛛创建一个“下一页”xpath 选择器,但我无法找出它的正确位置路径。
我一直在 Scrapy shell 环境中测试我的代码

这是我的蜘蛛源代码 - 使用 python3

import scrapy class StarbucksSpider(scrapy.Spider):
name = 'starbucks'
allowed_domains = ['gameflip.com/shop/gift-cards/starbucks']
start_urls = ['https://gameflip.com/shop/gift-cards/starbucks?limit=36&platform=starbucks&accept_currency=USD&status=onsale']

def parse(self, response):
    
    slots = response.xpath('//*[@class="listing-detail view-grid col-6 col-md-4 col-lg-3 col-xl-2"]')

    for slot in slots:

        fullPrice = slot.xpath('.//*[@class="col-12 description normal"]/text()').extract_first()
        Discount = slot.xpath('.//*[@class="badge badge-success listing-discount"]/text()').extract_first()
        price = slot.xpath('.//*[@class="money"]/text()').extract_first()
        status = slot.xpath('.//*[@alt="sold"]/@alt').extract_first()

        print ('\n')
        print (status)
        print (fullPrice)
        print (Discount)
        print (price)
        print ('\n')

        next_PageUrl = response.xpath('//*[@class="btn"]/@href').extract_first()
        absoulute_next_page_url = response.urljoin(next_PageUrl)
        yield scrapy.Request(absoulute_next_page_url)

请不要犹豫向我提问,以便更好地帮助您回答。 任何帮助表示赞赏;D

感谢您抽出宝贵时间和解答!

1 个答案:

答案 0 :(得分:0)

jwjhdev 的评论中所述,内容来自 API。 重新加载页面时,您可以在浏览器开发工具的网络选项卡中看到这一点。 API 的 url 可以修改为每页提供更多或更少的对象。 如果我们在您的情况下增加到 150,我们只会获得一页数据,这意味着一个请求:https://production-gameflip.fingershock.com/api/v1/listing?limit=150&kind=item&category=GIFTCARD&platform=starbucks&status=onsale&sort=_score:desc,shipping_within_days:asc,created:desc&accept_currency=USD

因此,我们可以查询 api 并获得更易于操作的结构化数据,而不是从网页中获取数据并必须使用 xpath。

我在下方稍微修改了您的爬虫代码,以展示我们如何从 API 获取数据。我们将使用上面的 API url 作为 start_urls 但是我注意到折扣不在响应中,所以我相信您必须在代码中计算它。

import json
import scrapy


class StarbucksSpider(scrapy.Spider):
    name = 'starbucks'
    start_urls = [
        'https://production-gameflip.fingershock.com/api/v1/listing?limit=150&kind=item&category=GIFTCARD&platform=starbucks&status=onsale&sort=_score:desc,shipping_within_days:asc,created:desc&accept_currency=USD'
    ]


    def parse(self, response):
        api_data = json.loads(response.text)
        slots = api_data.get('data')

        for slot in slots:
            fullPrice = slot.get('name')
            # I couldn't find in the json the discount
            Discount = 'TODO - Calculate discount using values from API'
            price = slot.get('price')
            status = slot.get('status')

            print('\n')
            print(status)
            print(fullPrice)
            print(Discount)
            print(price)
            print('\n')