如何使用 ZenRows Web Scraper 为无限滚动网站构建产品抓取器
在网页抓取领域,从使用无限滚动的网页中访问和提取数据对于开发人员来说可能是一个挑战。许多网站使用这种技术来动态加载更多内容,从而很难一次性抓取所有可用数据。一个好的解决方案涉及模拟用户操作,例如单击“加载更多”按钮以显示其他内容。
本教程将深入研究从无限滚动的页面中抓取产品数据,利用 Zenrows 开源网络抓取工具,您将构建一个抓取机器人来访问网页内容,并且您将使用 Zenrows 生成更多产品通过点击“加载更多”按钮,模拟无限滚动页面。
先决条件
要学习本教程,您需要具备以下条件:
- Python:您应该在您的计算机上设置 Python。如果没有,您可以在这里安装。
- 网页抓取基础:您应该充分掌握网页抓取的工作原理。
- ZenRows SDK:您将使用 ZenRows 服务绕过反抓取措施并简化抓取动态内容。您可以在此处注册免费的 ZenRows 帐户。
访问内容
注册 Zenrows 帐户并满足先决条件后,下一步就是从网页访问内容;在本教程中,您将使用此页面 https://www.scrapingcourse.com/button-click。
您还将使用 ZenRows SDK 来抓取动态页面并处理各种渲染和反机器人措施。让我们开始吧:
安装所需的库:
打开您首选 IDE 的终端并运行代码以安装 ZenRows Python SDK。
pip install zenrows python-dotenv
设置您的 API
前往仪表板并复制屏幕右上角的 API 密钥,如下图所示。
接下来,创建页面 app.py 和 .env,然后将以下代码添加到您的 app.py 文件中。并将您的 API 密钥添加到 .env 文件中的变量 API_KEY。
# Import ZenRows SDK from zenrows import ZenRowsClient from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Initialize ZenRows client with your API key client = ZenRowsClient(os.getenv("API_KEY")) # URL of the page you want to scrape url = "https://www.scrapingcourse.com/button-click" # Set up initial parameters for JavaScript rendering and interaction base_params = { "js_render": "true", "json_response": "true", "premium_proxy": "true", "markdown_response": "true" }
上面的代码使用您的 API 密钥启动 Zenrow SDK。它为您要抓取的网页设置 URL 变量,并为必要的参数建立 base_params 变量。您可以使用以下命令执行抓取工具:
python app.py
这将为您提供仅包含当前页面上的产品的页面的 HTML 表示。
.
您随时可以更进一步。
加载更多产品
为了增强您的抓取工具,您可以实现额外的参数来与网页底部的“加载更多”按钮交互并加载更多产品。
首先修改导入以包含必要的包并添加用于过滤产品响应的 parse_products 函数:
pip install zenrows python-dotenv
接下来,创建一个 while 循环,不断从多个页面中抓取产品信息,直到达到指定的限制 (max_products)。将本教程的限制设置为 50:
# Import ZenRows SDK from zenrows import ZenRowsClient from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Initialize ZenRows client with your API key client = ZenRowsClient(os.getenv("API_KEY")) # URL of the page you want to scrape url = "https://www.scrapingcourse.com/button-click" # Set up initial parameters for JavaScript rendering and interaction base_params = { "js_render": "true", "json_response": "true", "premium_proxy": "true", "markdown_response": "true" }
此循环将通过模拟单击“加载更多”按钮来继续报废产品,直到达到指定的限制。
解析产品信息
最后,您可以解析上一步中抓取的产品信息。对于每个产品,提取产品名称、图像链接、价格和产品页面 URL。您还可以计算所有产品的总价并打印结果,如下所示:
python app.py
解析为 CSV 文件
如果您希望将响应解析为导出的 CSV 文件,在接下来的几个步骤中,您将获取已抓取的产品信息并了解如何将其导出为 CSV 文件。
修改脚本以保存数据
首先,您需要使用Python内置的CSV模块来保存产品数据。 在本例中,每个产品都有四个主要属性:名称、image_link、价格和product_url。
您可以将它们用作 CSV 的标题,循环浏览已抓取产品的列表,然后将每个产品作为一行写入 CSV 文件中。
import re import json import time def parse_products(response_json): try: data = json.loads(response_json) md_content = data.get('md', '') pattern = r'\[!\[([^\]]+)\]\(([^\)]+)\)\*\n([^\\n]+)\*\n\*\n$(\d+)\]\(([^\)]+)\)' matches = re.findall(pattern, md_content) products = [] for match in matches: product = { 'name': match[0], 'image_link': match[1], 'price': int(match[3]), 'product_url': match[4] } products.append(product) return products except json.JSONDecodeError: print("Error: Unable to parse JSON response") print("Response content:", response_json[:500]) return [] except Exception as e: print(f"Error parsing products: {str(e)}") return [] # Zenrow SDK code here
现在,抓取数据后,只需调用 save_to_csv(all_products) 函数即可将数据存储在名为 products.csv 的 CSV 文件中。
抓取过程完成后,运行命令自动将数据保存到 CSV 文件。
# Zenrow SDK code goes here max_products = 50 all_products = [] page = 1 while len(all_products) < max_products: print(f"Scraping page {page}...") # Update parameters for each request params = base_params.copy() js_instructions = [{"click": "#load-more-btn"} for _ in range(page)] js_instructions.append({"wait": 5000}) params["js_instructions"] = json.dumps(js_instructions) try: # Send the GET request to ZenRows response = client.get(url, params=params) # Parse the response JSON new_products = parse_products(response.text) if not new_products: print("No more products found. Stopping.") break all_products.extend(new_products) print(f"Found {len(new_products)} products on this page.") print(f"Total products so far: {len(all_products)}") page += 1 # Add a delay to avoid overwhelming the server time.sleep(2) except Exception as e: print(f"Error occurred: {str(e)}") break
确定 5 种价格最高的产品
现在您已经拥有了结构化格式的所有产品,您可以更进一步确定 5 个价格最高的产品,并且您必须访问每个产品页面以提取额外的详细信息,例如产品描述和 SKU代码。
按价格对产品进行排序:使用Python的sorted()函数,可以将产品列表按价格降序排序,并检索前5个产品。
您需要使用 requests.get() 函数访问每个页面以获取每个页面的产品数据。从响应中,您可以提取产品描述和 SKU 代码。
您还可以更新上一步的 csv 文件以包含其他详细信息。
这是实现这一目标的代码:
# Updated Params and while loop code goes here # Calculate the total price of all products total_sum = sum(product['price'] for product in all_products) print("\nAll products:") for product in all_products: print(product) # Print the total sum of the product prices print(f"\nTotal number of products: {len(all_products)}") print(f"Total sum of product prices: ${total_sum}")
现在,抓取后,您现在可以识别价格最高的产品:
pip install zenrows python-dotenv
检索附加信息后,您可以修改 CSV 文件或创建包含这些详细信息的新文件。
完整代码
完整的 app.py 文件应如下所示。
# Import ZenRows SDK from zenrows import ZenRowsClient from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Initialize ZenRows client with your API key client = ZenRowsClient(os.getenv("API_KEY")) # URL of the page you want to scrape url = "https://www.scrapingcourse.com/button-click" # Set up initial parameters for JavaScript rendering and interaction base_params = { "js_render": "true", "json_response": "true", "premium_proxy": "true", "markdown_response": "true" }
这是成功响应的样子。
python app.py
查看 GitHub 上的完整代码库。
结论
在本教程中,您学习了如何使用“加载更多”按钮从无限滚动的网页中抓取产品。通过遵循概述的步骤,您可以使用 ZenRows 提取有价值的产品信息并增强您的抓取技术。
要了解有关如何使用 Zenrow 网页抓取工具的更多信息,请查看我们博客上的以下文章。
- 如何用 PHP 解析 HTML
- 如何使用 Hrequests 进行网页抓取
- 如何在 Ruby 中使用 playwright 这是一个关于使用 Zenrows 网络抓取工具的无代码方法的快速视频。
以上是如何使用 ZenRows Web Scraper 为无限滚动网站构建产品抓取器的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
