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

元素在检查器中可见仍触发NoSuchElementException问题解决

问题:Selenium已确认目标元素存在但find_element仍执行失败

问题详情

使用Python和Selenium爬取网页时,网页已完全加载,且在WebDriver打开的浏览器中通过检查器能看到目标元素<div class="predictions-container">,但调用find_element方法时始终抛出selenium.common.exceptions.NoSuchElementException。

原问题代码

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 是否要正确等待元素加载?[未使用]
from selenium.webdriver.common.by import By # 定位元素方式
import time


sURL = 'https://theanalyst.com/eu/2023/07/fifa-womens-world-cup-stats-2023-opta/'

myChromeOptions = webdriver.ChromeOptions()
#myChromeOptions.add_argument("--headless") # 后续想用无头模式,但现在需要可视化调试
driver = webdriver.Chrome(options = myChromeOptions)
driver.get(sURL)

time.sleep(100) # 等待足够长时间,确保在打开的浏览器中能看到目标数据
# 此时在WebDriver的Chrome浏览器中检查元素,能找到目标<div class="predictions-container">

element = driver.find_element(By.CLASS_NAME, "predictions-container") # 抛出selenium.common.exceptions.NoSuchElementException

问题原因与解决方法

  1. iframe上下文切换:目标元素位于id为iFrameResizer0的iframe内部,Selenium默认在主页面文档中查找元素,必须先切换到该iframe的上下文才能定位到内部元素。
  2. 替换低效等待:原代码使用time.sleep()的固定等待不够可靠,改用WebDriverWait结合预期条件的显式等待,能在元素出现后立即执行后续操作,提升效率和稳定性。

修正后的代码

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 正确等待元素加载
from selenium.webdriver.support import expected_conditions as EC # 针对特定元素的智能等待
from selenium.webdriver.common.by import By # 定位元素方式

sURL = 'https://theanalyst.com/eu/2023/07/fifa-womens-world-cup-stats-2023-opta/'

myChromeOptions = webdriver.ChromeOptions()
myChromeOptions.add_argument("--headless") # 现在可以正常使用无头模式了!
driver = webdriver.Chrome(options = myChromeOptions)
driver.get(sURL)
driver.switch_to.frame(driver.find_element(By.ID, "iFrameResizer0")) # 切换到目标iframe上下文
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "predictions-container"))) # 显式等待目标元素出现
element = driver.find_element(By.CLASS_NAME, "predictions-container") # 现在可以正常定位元素了
# 在这里对element进行操作,切换回主文档后element会失效,抛出StaleElementReferenceException
driver.switch_to.default_content() # 切换回主页面文档,方便后续操作其他元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:59:53