python - 是否可以在不使用 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)
解决方案
向下滚动时直接使用在后台发出的请求。当您检查网站的源代码 (ctrl + u) 或使用浏览器的 DevTools (ctrl + shift + c) 并检查网络选项卡或控制台选项卡时,您会发现它。查看向下滚动后会发生什么。您应该注意到他们的 API 发出了一些请求,您可以使用和操作这些请求来获取您正在寻找的数据。
更改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']
}
推荐阅读
- node.js - 在没有 nginx 的 Node / Angular 应用程序中创建动态子域
- c++ - 来自 std::chrono 的编译器警告但未被使用
- swift - 如何将 UIAlertController 操作表锚定到特定单元格 UICollectionView?
- java - 静态方法中的同步块将获取类级别锁或对象级别锁
- sql - Postgres - 在返回多行后选择一行
- shell - 使用 pod 获取 kubernetes 节点上的设备挂载信息
- python - 使用 SequenceMatcher 在 python 中使用 numba 加速
- java - GCP Spanner 中的动态查询生成器
- javascript - 如何自定义 Intl.DateTimeFormat 日期?
- xml - 如何读取具有多个元素的 xml 文件并使用进度 4gl dom 写入临时表?