首页 > 解决方案 > 是否可以在不使用 Selenium 的情况下使用 Python 抓取无限滚动的网站?

问题描述

我正在尝试从网站上抓取信息。我能够很好地抓取加载的初始页面,但它一次只能加载 24 个项目。您必须不断向下滚动到页面底部以强制加载接下来的 24 项。我在网上找到的唯一解决方案需要 Selenium。

html_path = 'https://www.nike.com/w/mens-shoes-nik1zy7ok'
raw_html = simple_get(html_path)
html = BeautifulSoup(raw_html, 'html.parser')

'''
for div in html.select('div'):
    if div['class'] == 'product-card__title':
        print(div.text)
        '''
shoes = html.find_all("div", {"class" : "product-card__title"})
for i in shoes:
    print(i.text)

标签: pythonseleniumweb-scrapingscrapy

解决方案


向下滚动时直接使用在后台发出的请求。当您检查网站的源代码 (ctrl + u) 或使用浏览器的 DevTools (ctrl + shift + c) 并检查网络选项卡或控制台选项卡时,您会发现它。查看向下滚动后会发生什么。您应该注意到他们的 API 发出了一些请求,您可以使用和操作这些请求来获取您正在寻找的数据。

如果我对在德国(“DE”)销售的男鞋感兴趣,这里是一个示例电话:
https ://www.nike.com/product_feed/rollup_threads/v2?filter=marketplace(DE)&filter=language (de)&filter=employeePrice(true)&filter=attributeIds(0f64ecc7-d624-4e91-b171-b83a03dd8550%2C16633190-45e5-4830-a068-232ac7aea82c%2C5b21a62a-0503-400c-8336-3ccfbff2a684)&anchor=0&consumerChannelId=d9a5bc42-4b9c -4976-858a-f159cf99c647&count=24

更改anchor-value 以设置起始项。在我的示例中,我想从顶部开始,因此将其设置为 0。
更改count-value 以设置响应中包含的项目数量。

响应将采用 json 格式。例如,如果您想在响应中提取鞋子的名称、所有鞋子的全价和折扣当前价格,您可以执行以下操作:

import scrapy
import json


class NikeSpider(scrapy.Spider):
    name = "nike"
    start_urls = ['https://www.nike.com/product_feed/rollup_threads/v2?filter=marketplace(DE)&filter=language(de)&filter=employeePrice(true)&filter=attributeIds(0f64ecc7-d624-4e91-b171-b83a03dd8550%2C16633190-45e5-4830-a068-232ac7aea82c%2C5b21a62a-0503-400c-8336-3ccfbff2a684)&anchor=0&consumerChannelId=d9a5bc42-4b9c-4976-858a-f159cf99c647&count=24']

    def parse(self, response):
        jsonresponse = json.loads(response.body_as_unicode())

        for shoe in jsonresponse['objects']:
            yield {
                'Shoe Title': shoe['publishedContent']['properties']['title'],
                'Full Price': shoe['productInfo'][0]['merchPrice']['fullPrice'],
                'Discounted Price': shoe['productInfo'][0]['merchPrice']['currentPrice']
            }


推荐阅读