使用'加载更多”按钮抓取无限滚动页面:分步指南
尝试从动态网页加载数据时,您的抓取工具是否卡住了?您是否对无限滚动或那些讨厌的“加载更多”按钮感到沮丧?
你并不孤单。如今,许多网站都实施这些设计来改善用户体验,但它们对于网络抓取工具来说可能具有挑战性。
本教程将指导您完成适合初学者的演练,使用 加载更多 按钮抓取演示页面。目标网页如下所示:
最后,您将学习如何:
- 设置 Selenium 进行网页抓取。
- 自动化“加载更多”按钮交互。
- 提取产品数据,例如名称、价格和链接。
让我们开始吧!
第 1 步:先决条件
开始之前,请确保满足以下先决条件:
- 已安装 Python:从 python.org 下载并安装最新的 Python 版本,包括安装过程中的 pip。
- 基础知识:熟悉网页抓取概念、Python 编程以及使用 requests、BeautifulSoup 和 Selenium 等库。
所需的图书馆:
- 请求:用于发送 HTTP 请求。
- BeautifulSoup:用于解析 HTML 内容。
- Selenium:用于模拟用户交互,例如浏览器中的按钮单击。
您可以在终端中使用以下命令安装这些库:
pip install requests beautifulsoup4 selenium
在使用 Selenium 之前,您必须安装与您的浏览器匹配的网络驱动程序。在本教程中,我们将使用 Google Chrome 和 ChromeDriver。不过,您可以对 Firefox 或 Edge 等其他浏览器执行类似的步骤。
安装网络驱动程序
- 检查您的浏览器版本:
打开 Google Chrome 并导航至 帮助 >关于 Google Chrome 从三点菜单中查找 Chrome 版本。
下载 ChromeDriver:
访问 ChromeDriver 下载页面。
下载与您的 Chrome 版本匹配的驱动程序版本。
将 ChromeDriver 添加到您的系统路径:
解压下载的文件并将其放置在 /usr/local/bin (Mac/Linux) 或 C:WindowsSystem32 (Windows) 等目录中。
验证安装
在项目目录中初始化一个 Python 文件 scraper.py 并通过运行以下代码片段测试一切设置是否正确:
from selenium import webdriver driver = webdriver.Chrome() # Ensure ChromeDriver is installed and in PATH driver.get("https://www.scrapingcourse.com/button-click") print(driver.title) driver.quit()
您可以通过在终端上运行以下命令来执行上述文件代码:
pip install requests beautifulsoup4 selenium
如果上面的代码运行没有错误,它将启动浏览器界面并打开演示页面 URL,如下所示:
Selenium 随后将提取 HTML 并打印页面标题。你会看到这样的输出 -
from selenium import webdriver driver = webdriver.Chrome() # Ensure ChromeDriver is installed and in PATH driver.get("https://www.scrapingcourse.com/button-click") print(driver.title) driver.quit()
这将验证 Selenium 是否可以使用。安装所有要求并准备使用后,您可以开始访问演示页面的内容。
第 2 步:访问内容
第一步是获取页面的初始内容,这将为您提供页面 HTML 的基线快照。这将帮助您验证连接并确保抓取过程的有效起点。
您将通过使用 Python 中的 Requests 库发送 GET 请求来检索页面 URL 的 HTML 内容。代码如下:
python scraper.py
上面的代码将输出包含前 12 个产品数据的原始 HTML。
HTML 的快速预览可确保请求成功并且您正在使用有效的数据。
第 3 步:加载更多产品
要访问剩余的产品,您需要以编程方式单击页面上的“加载更多”按钮,直到没有更多产品可用。由于此交互涉及 JavaScript,因此您将使用 Selenium 来模拟按钮单击。
在编写代码之前,我们先检查一下页面以定位:
- “加载更多” 按钮选择器 (load-more-btn)。
- 保存产品详细信息的 div (product-item)。
您将通过加载更多产品来获得所有产品,通过运行以下代码为您提供更大的数据集:
Load More Button Challenge to Learn Web Scraping - ScrapingCourse.com
此代码打开浏览器,导航到页面,并与“加载更多”按钮交互。然后提取更新后的 HTML(现在包含更多产品数据)。
如果你不希望Selenium每次运行这段代码时都打开浏览器,它还提供了无头浏览器功能。无头浏览器具有实际 Web 浏览器的所有功能,但没有图形用户界面 (GUI)。
您可以通过定义 ChromeOptions 对象并将其传递给 WebDriver Chrome 构造函数,在 Selenium 中启用 Chrome 的无头模式,如下所示:
import requests # URL of the demo page with products url = "https://www.scrapingcourse.com/button-click" # Send a GET request to the URL response = requests.get(url) # Check if the request was successful if response.status_code == 200: html_content = response.text print(html_content) # Optional: Preview the HTML else: print(f"Failed to retrieve content: {response.status_code}")
当您运行上述代码时,Selenium 将启动一个无头 Chrome 实例,因此您将不再看到 Chrome 窗口。这对于在服务器上运行抓取脚本时不想在 GUI 上浪费资源的生产环境来说是理想的选择。
现在已检索到完整的 HTML 内容,是时候提取有关每个产品的具体详细信息了。
第四步:解析产品信息
在此步骤中,您将使用 BeautifulSoup 解析 HTML 并识别产品元素。然后,您将提取每个产品的关键详细信息,例如名称、价格和链接。
pip install requests beautifulsoup4 selenium
在输出中,您应该看到产品详细信息的结构化列表,包括名称、图像 URL、价格和产品页面链接,如下所示 -
from selenium import webdriver driver = webdriver.Chrome() # Ensure ChromeDriver is installed and in PATH driver.get("https://www.scrapingcourse.com/button-click") print(driver.title) driver.quit()
上面的代码将原始 HTML 数据组织成结构化格式,使其更容易使用和准备输出数据以进行进一步处理。
第 5 步:将产品信息导出到 CSV
您现在可以将提取的数据组织到 CSV 文件中,这使得分析或共享变得更加容易。 Python 的 CSV 模块对此有所帮助。
python scraper.py
上述代码将创建一个新的 CSV 文件,其中包含所有必需的产品详细信息。
以下是概述的完整代码:
Load More Button Challenge to Learn Web Scraping - ScrapingCourse.com
上面的代码将创建一个 products.csv,如下所示:
import requests # URL of the demo page with products url = "https://www.scrapingcourse.com/button-click" # Send a GET request to the URL response = requests.get(url) # Check if the request was successful if response.status_code == 200: html_content = response.text print(html_content) # Optional: Preview the HTML else: print(f"Failed to retrieve content: {response.status_code}")
第 6 步:获取热门产品的额外数据
现在,假设您想要识别价格最高的前 5 个产品,并从其各个页面中提取其他数据(例如产品描述和 SKU 代码)。您可以使用以下代码来做到这一点:
from selenium import webdriver from selenium.webdriver.common.by import By import time # Set up the WebDriver (make sure you have the appropriate driver installed, e.g., ChromeDriver) driver = webdriver.Chrome() # Open the page driver.get("https://www.scrapingcourse.com/button-click") # Loop to click the "Load More" button until there are no more products while True: try: # Find the "Load more" button by its ID and click it load_more_button = driver.find_element(By.ID, "load-more-btn") load_more_button.click() # Wait for the content to load (adjust time as necessary) time.sleep(2) except Exception as e: # If no "Load More" button is found (end of products), break out of the loop print("No more products to load.") break # Get the updated page content after all products are loaded html_content = driver.page_source # Close the browser window driver.quit()
以下是概述的完整代码:
from selenium import webdriver from selenium.webdriver.common.by import By import time # instantiate a Chrome options object options = webdriver.ChromeOptions() # set the options to use Chrome in headless mode options.add_argument("--headless=new") # initialize an instance of the Chrome driver (browser) in headless mode driver = webdriver.Chrome(options=options) ...
此代码按价格降序对产品进行排序。然后,对于价格最高的前 5 个产品,脚本打开其产品页面并使用 BeautifulSoup 提取产品描述和 SKU。
上面代码的输出将是这样的:
from bs4 import BeautifulSoup # Parse the page content with BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') # Extract product details products = [] # Find all product items in the grid product_items = soup.find_all('div', class_='product-item') for product in product_items: # Extract the product name name = product.find('span', class_='product-name').get_text(strip=True) # Extract the product price price = product.find('span', class_='product-price').get_text(strip=True) # Extract the product link link = product.find('a')['href'] # Extract the image URL image_url = product.find('img')['src'] # Create a dictionary with the product details products.append({ 'name': name, 'price': price, 'link': link, 'image_url': image_url }) # Print the extracted product details for product in products[:2]: print(f"Name: {product['name']}") print(f"Price: {product['price']}") print(f"Link: {product['link']}") print(f"Image URL: {product['image_url']}") print('-' * 30)
上面的代码将更新 products.csv,它现在将具有如下信息:
Name: Chaz Kangeroo Hoodie Price: Link: https://scrapingcourse.com/ecommerce/product/chaz-kangeroo-hoodie Image URL: https://scrapingcourse.com/ecommerce/wp-content/uploads/2024/03/mh01-gray_main.jpg ------------------------------ Name: Teton Pullover Hoodie Price: Link: https://scrapingcourse.com/ecommerce/product/teton-pullover-hoodie Image URL: https://scrapingcourse.com/ecommerce/wp-content/uploads/2024/03/mh02-black_main.jpg ------------------------------ …
结论
使用无限滚动或“加载更多”按钮抓取页面似乎具有挑战性,但使用 Requests、Selenium 和 BeautifulSoup 等工具可以简化该过程。
本教程展示了如何从演示页面检索和处理产品数据,并将其保存为结构化格式以便快速轻松地访问。
在此处查看所有代码片段。
以上是使用'加载更多”按钮抓取无限滚动页面:分步指南的详细内容。更多信息请关注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)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。 Python以简洁和强大的生态系统着称,C 则以高性能和底层控制能力闻名。

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python在游戏和GUI开发中表现出色。1)游戏开发使用Pygame,提供绘图、音频等功能,适合创建2D游戏。2)GUI开发可选择Tkinter或PyQt,Tkinter简单易用,PyQt功能丰富,适合专业开发。

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。
