You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python抓取触发JavaScript后的动态页面数据?

解决Selenium抓取JavaScript动态更新内容的问题

你碰到的问题很典型——Selenium默认只会加载页面的初始状态,不会自动触发页面上的交互操作。你的代码直接获取元素内容时,按钮还没被点击,所以拿到的是初始的Hello,而不是点击后JS更新的GoodBye。

只需要在获取元素前,先触发按钮的点击事件就行,下面是修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_path = "C:\\Users\\Antonio\\Downloads\\chromedriver_win32\\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

try:
    driver.get("http://localhost/templates/scraping.html")
    
    # 定位页面上的"Try it"按钮并点击,触发JS函数
    try_it_button = driver.find_element(By.XPATH, "//button[@onclick='myFunction()']")
    try_it_button.click()
    
    # 点击后,定位目标元素并获取更新后的文本
    target_element = driver.find_element(By.ID, "yesnojs")
    print(target_element.text)
finally:
    # 确保浏览器会被关闭,避免残留进程
    driver.quit()

几个关键说明:

  • 必须触发点击操作:这是让JS执行并更新元素内容的核心步骤,没有这一步,页面永远停留在初始状态
  • 用ID定位更精准:你的目标元素有唯一的id="yesnojs",直接用By.ID定位比class更可靠,不会因为页面有其他同class元素而出错
  • 加入try-finally块:不管操作是否成功,都会关闭浏览器,防止ChromeDriver进程在后台残留

如果遇到页面加载慢或者JS执行有延迟的情况,还可以加入显式等待来确保元素文本已经更新:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_path = "C:\\Users\\Antonio\\Downloads\\chromedriver_win32\\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

try:
    driver.get("http://localhost/templates/scraping.html")
    
    try_it_button = driver.find_element(By.XPATH, "//button[@onclick='myFunction()']")
    try_it_button.click()
    
    # 等待最多10秒,直到元素文本变为"GoodBye"
    wait = WebDriverWait(driver, 10)
    wait.until(EC.text_to_be_present_in_element((By.ID, "yesnojs"), "GoodBye"))
    
    target_element = driver.find_element(By.ID, "yesnojs")
    print(target_element.text)
finally:
    driver.quit()

这样就能保证你拿到的是按钮点击后的动态更新内容啦!

内容的提问来源于stack exchange,提问作者AntonioMJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:19:28