
本文旨在指导初学者使用 Selenium 和 Python 抓取网页中点击按钮后更新的 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() #关闭浏览器代码解释:
注意事项:
如果点击按钮后页面会跳转到新的 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()代码解释:
总结:
本文介绍了如何使用 Selenium 和 Python 抓取点击按钮后更新的 HTML 代码。 重点介绍了如何通过文本定位元素、使用显式等待确保元素加载完成,以及如何处理页面跳转的情况。 通过这些技巧,可以更有效地抓取动态网页的数据。记住要根据实际情况调整代码,例如修改元素定位方式、调整等待时间等。
以上就是使用 Selenium 和 Python 抓取点击按钮后网页的 HTML 代码的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号