
本文旨在指导初学者使用 Selenium 和 Python 抓取网页中点击按钮后更新的 HTML 代码。通过示例代码演示如何定位按钮并模拟点击,以及如何获取每次点击后的完整页面源代码。我们将重点介绍如何通过文本定位元素,并处理页面跳转的情况,确保能够完整抓取每次点击后的页面数据。
使用 Selenium 抓取动态网页 HTML 代码
在Web数据抓取中,经常会遇到需要与网页进行交互的情况,例如点击按钮后页面内容才会更新。Selenium 结合 Python 提供了一种强大的解决方案,可以模拟用户行为,抓取动态生成的 HTML 代码。
定位和点击按钮
首先,我们需要使用 Selenium 定位到需要点击的按钮。 推荐使用按钮上的文本内容进行定位,因为文本通常比 XPath 更稳定。
以下代码演示了如何使用按钮文本定位元素并进行点击:
立即学习“Python免费学习笔记(深入)”;
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.headless = True # 设置为无头模式,不在图形界面中显示浏览器
# options.binary_location = r'/bin/firefox' # 如果 Firefox 的二进制文件不在默认路径,需要指定
driver = webdriver.Firefox(options=options)
driver.set_window_size(1920, 1080) #设置窗口大小,方便调试
driver.get('https://blabla.bla') # 替换为你的目标网页
all_htmls = []
# 定义一个函数,用于点击按钮并获取 HTML 代码
def click_button_and_get_html(button_text):
try:
# 使用 WebDriverWait 确保元素加载完成
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, button_text))
)
button.click()
# 获取点击后的 HTML 代码
html_code = driver.page_source
all_htmls.append(html_code)
print(f"Successfully clicked button '{button_text}' and captured HTML.")
except Exception as e:
print(f"Error clicking button '{button_text}': {e}")
# 依次点击按钮并获取 HTML 代码
click_button_and_get_html("Banana")
click_button_and_get_html("Apple")
click_button_and_get_html("Orange")
# 打印所有获取到的 HTML 代码数量
print(f"Total HTMLs captured: {len(all_htmls)}")
driver.quit() #关闭浏览器代码解释:
- 导入必要的库: 导入 selenium 相关模块,包括 webdriver、By(用于元素定位)、Options(用于配置浏览器选项)和 WebDriverWait (显式等待)
- 配置浏览器选项: 设置 headless 为 True 可以在后台运行浏览器,无需显示界面。
- 创建 WebDriver 实例: 创建 Firefox 的 WebDriver 实例,并传入配置选项。
- 打开网页: 使用 driver.get() 方法打开目标网页。
-
定义 click_button_and_get_html 函数:
- 使用 WebDriverWait 和 EC.element_to_be_clickable 确保按钮可以点击。
- 使用 By.LINK_TEXT 通过链接文本定位按钮。
- 点击按钮后,使用 driver.page_source 获取当前页面的 HTML 代码。
- 将获取到的 HTML 代码添加到 all_htmls 列表中。
- 依次点击按钮: 调用 click_button_and_get_html 函数,依次点击 "Banana"、"Apple" 和 "Orange" 按钮,并获取每次点击后的 HTML 代码。
- 打印结果: 打印 all_htmls 列表中 HTML 代码的数量。
- 关闭浏览器: 使用 driver.quit() 方法关闭浏览器,释放资源。
注意事项:
操作系统概述效益型网站第一品牌,一切为了效益,感谢您使用效益型V1.0网站后台管理系统。窗口中的用户名和密码。当用户输入用户名和密码之后,用鼠标左键点击确定按钮即可进入系统。如果用户忘记密码,可点击这里找回进入找回密码页面,提交用户名和E-mail找回密码, E-mail必须是该系统内企业的E-mail。窗口为用户登录后的操作系统界面,界面框架主要由头部、左部、右部(主窗口)三部分组成。1. 头部
- 显式等待: 使用 WebDriverWait 和 expected_conditions 可以确保在元素加载完成后再进行操作,避免因元素未加载完成而导致的错误。 EC.element_to_be_clickable 用于等待元素可点击。
- 错误处理: 在 click_button_and_get_html 函数中使用 try...except 块捕获异常,可以防止程序因某个按钮点击失败而崩溃。
- 浏览器驱动: 确保已安装与你的浏览器版本匹配的 WebDriver,并将其添加到系统环境变量 PATH 中,或者在代码中指定 WebDriver 的路径。
- 页面跳转: 如果点击按钮会导致页面跳转到不同的 URL,需要在每次点击后使用 driver.back() 返回到原始页面,才能继续点击其他按钮。
- 元素定位: 如果按钮文本不唯一,可以考虑使用其他定位方式,例如 By.XPATH、By.CSS_SELECTOR 等。
处理页面跳转
如果点击按钮后页面会跳转到新的 URL,需要在获取 HTML 代码后返回到原始页面,才能继续点击其他按钮。
以下代码演示了如何处理页面跳转的情况:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
driver.set_window_size(1920, 1080)
driver.get('https://blabla.bla')
all_htmls = []
def click_button_and_get_html(button_text):
try:
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, button_text))
)
button.click()
# 获取点击后的 HTML 代码
html_code = driver.page_source
all_htmls.append(html_code)
print(f"Successfully clicked button '{button_text}' and captured HTML.")
# 返回到原始页面
driver.back()
# 重新加载原始页面,避免 stale element reference exception
driver.get('https://blabla.bla')
except Exception as e:
print(f"Error clicking button '{button_text}': {e}")
click_button_and_get_html("Banana")
click_button_and_get_html("Apple")
click_button_and_get_html("Orange")
print(f"Total HTMLs captured: {len(all_htmls)}")
driver.quit()代码解释:
- 在 click_button_and_get_html 函数中,点击按钮后,使用 driver.back() 方法返回到原始页面。
- 使用driver.get('https://blabla.bla')重新加载原始页面,避免stale element reference exception。
总结:
本文介绍了如何使用 Selenium 和 Python 抓取点击按钮后更新的 HTML 代码。 重点介绍了如何通过文本定位元素、使用显式等待确保元素加载完成,以及如何处理页面跳转的情况。 通过这些技巧,可以更有效地抓取动态网页的数据。记住要根据实际情况调整代码,例如修改元素定位方式、调整等待时间等。










