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

Selenium NoSuchElementException:无法定位PubChem页面下载按钮

Selenium点击PubChem Download按钮出现NoSuchElementException的解决办法

问题根源

  • XPath语法错误:原代码里的XPath引号嵌套混乱,//*[@id='"'page-download-btn'"'] 这种写法会导致解析错误,无法定位到元素。
  • 未等待页面渲染完成:直接调用find_element时,页面可能还在加载,目标元素尚未生成,从而触发异常。

修复步骤

1. 修正定位表达式

直接通过ID定位更简洁可靠,也可以修正XPath写法:

  • 通过ID定位:By.ID, 'page-download-btn'
  • 修正后的XPath://*[@id='page-download-btn'] 或 //*[@id="page-download-btn"]

2. 添加显式等待

用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
from selenium.webdriver.chrome.options import Options
import time

options = webdriver.ChromeOptions()
# 路径加r前缀避免转义字符问题
driver_path = r'C:\Users\Idener\Downloads\chromedriver_win32\chromedriver.exe'
driver = webdriver.Chrome(driver_path, options=options)
url = "https://pubchem.ncbi.nlm.nih.gov/compound/2078"
driver.get(url)

try:
    # 最长等待10秒,直到Download按钮可点击
    download_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, 'page-download-btn'))
    )
    download_btn.click()
except Exception as e:
    print(f"操作失败: {str(e)}")
finally:
    # 根据需要选择是否关闭浏览器
    # driver.quit()
    pass

额外提示

  • Windows路径中的反斜杠需要处理:要么加r前缀转为原始字符串,要么写成\\避免转义。
  • 确保ChromeDriver版本与本地Chrome浏览器版本一致,版本不兼容也可能引发各类异常。

内容的提问来源于stack exchange,提问作者Sara Gil Guerrero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:40:25