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

Selenium 4.7.2按name定位元素报NoSuchElementException问题排查

问题排查与解决

核心问题

你遇到的NoSuchElementException主要有两个关键原因:元素未完成加载就执行查找,或者使用了错误的属性值进行定位。

1. 页面未加载完成导致元素不可见

Selenium调用browser.get()后,页面可能仍在异步渲染,直接执行find_element会因元素尚未出现在DOM中而报错。

解决:用显式等待替代固定延迟
显式等待会等待元素满足条件后再执行操作,比time.sleep更可靠:

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

browser = webdriver.Chrome()
browser.get('https://www.woofshack.com/en/cloud-chaser-waterproof-softshell-dog-jacket-ruffwear-rw-5102.html')

# 最长等待10秒,直到元素被定位到
price = WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.ID, 'data-price-665'))
)
print("Price: " + price.text)

browser.close()

2. 定位属性错误

通过检查目标页面的DOM结构,不存在name="data-price-665"的元素,该价格元素的实际id为data-price-665。你误将id属性当作name来使用,导致定位失败。

修正:使用正确的定位方式

  • 按ID定位(最直接):
price = browser.find_element(By.ID, 'data-price-665')
  • 或按CSS选择器定位(如果需要通过价格值匹配):
price = browser.find_element(By.CSS_SELECTOR, '[data-price="665"]')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:00:41