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

为什么Selenium无法定位并点击目标按钮,且元素不在page_source中?

问题解决方法

问题原因

  • 目标站点存在自动化访问检测,识别到Selenium特征后会拒绝渲染页面内容,导致driver.page_source返回的body标签为空,无法定位到元素。
  • 固定等待time.sleep()稳定性不足,容易受网络、页面渲染速度影响,可能出现元素还未加载完成就执行查找逻辑的情况。

修复后的完整代码

from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "chromedriver"
# 配置反检测参数
chrome_options = Options()
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option("useAutomationExtension", False)

driver = webdriver.Chrome(PATH, options=chrome_options)
# 移除navigator.webdriver特征,进一步绕过检测
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

driver.get("https://suttacentral.net/mn86/en/sujato")

# 显式等待元素加载到可点击状态,最长等待20秒
try:
    view_btn = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.ID, "btnTools"))
    )
    # 点击目标按钮
    view_btn.click()
finally:
    # 可根据需求调整是否自动关闭浏览器
    time.sleep(5)
    driver.quit()

关键修改说明

  • 添加Chrome浏览器反检测配置,屏蔽Selenium的自动化特征,绕过站点访问限制,让页面可以正常渲染内容,driver.page_source就能正常返回完整页面代码。
  • 替换固定等待为显式等待WebDriverWait,主动监听目标元素状态,元素加载完成后立刻执行后续操作,兼容性和稳定性更高。
  • 采用Selenium官方推荐的find_element+By参数的写法,兼容新旧版本Selenium。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:24:03