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

求助:Selenium NoSuchElementException(Uniprot页面元素定位失败)

问题排查与解决方案

可能的原因及对应解决方法:

  1. 固定等待不可靠,改用显式等待
    固定sleep(15)无法保证元素已完成渲染——网络波动、页面动态加载都会导致元素加载时间不确定。换成Selenium的显式等待,会主动等待元素出现后再执行定位,稳定性更高。

  2. 选择器依赖层级索引,易失效
    你用的XPATH和CSS选择器都依赖元素的层级位置(比如div[2]、li:nth-child(2)),一旦页面结构微调(比如新增功能模块),这些索引就会失效。改用结合文本和类名的精准选择器,能避免这个问题。

  3. 无头模式窗口尺寸问题
    无头Chrome默认窗口极小,可能导致页面布局错乱、元素未渲染。设置合适的窗口尺寸即可解决。

修改后的代码示例:

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_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--window-size=1920,1080")  # 解决无头模式窗口过小问题

wd = webdriver.Chrome('chromedriver', options=chrome_options)
wd.get('https://www.uniprot.org/uniprotkb/Q14050/entry')

# 显式等待元素可见,最长等待20秒
molmass_element = WebDriverWait(wd, 20).until(
    EC.visibility_of_element_located(
        (By.XPATH, "//li[contains(., 'Mass')]/div/div[@class='decorated-list-item__content']")
    )
)
print(molmass_element.text)  # 输出:63,616

wd.quit()

额外排查点:

如果以上方法仍无效,检查元素是否在<iframe>标签内:打开开发者工具,查看目标元素的父级是否包含iframe。如果是,需要先切换到iframe再定位:

# 假设iframe的id是"target-iframe"
iframe = wd.find_element(By.ID, "target-iframe")
wd.switch_to.frame(iframe)
# 之后再执行元素定位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:00:59