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

Python Selenium无法定位CAS编号搜索框问题咨询

解决EFSA OpenFoodTox CAS编号搜索框定位问题

问题根源

代码停滞的核心原因有三点:

  1. 动态元素ID:mstr688是MicroStrategy生成的动态ID,每次页面加载都会变化,无法稳定定位元素。
  2. 未切换到iframe:OpenFoodTox的核心内容嵌入在独立iframe中,直接在主页面搜索元素会找不到目标。
  3. 等待条件不匹配:presence_of_element_located仅确保元素存在,但不保证它处于可交互状态,对于需要点击激活的元素,应该使用element_to_be_clickable。

修正后的代码

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
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()  # 替换为你使用的浏览器驱动

try:
    driver.get('https://www.efsa.europa.eu/en/microstrategy/openfoodtox')
    
    # 接受Cookie协议
    cookie_agree = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'ppms_cm_agree-to-all')))
    cookie_agree.click()
    
    # 切换到MicroStrategy内容所在的iframe
    iframe = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.ID, 'mstrContentFrame')))
    driver.switch_to.frame(iframe)
    
    # 定位并点击CAS编号搜索框的激活容器
    cas_container = WebDriverWait(driver, 15).until(EC.element_to_be_clickable(
        (By.XPATH, "//div[text()='CAS number']/preceding-sibling::div[contains(@class, 'mstrmojo-Button')]")
    ))
    cas_container.click()
    
    # 等待输入框加载完成并发送CAS编号
    cas_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.mstrmojo-TextBox")))
    cas_input.send_keys("你的CAS编号")  # 替换为实际需要查询的CAS编号
    cas_input.send_keys(Keys.ENTER)
    
finally:
    # 按需关闭浏览器,调试阶段可注释此行
    # driver.quit()
    pass

关键改进说明

  • iframe切换:通过driver.switch_to.frame()进入内容所在的iframe,确保能访问内部元素。
  • 稳定定位器:使用文本"CAS number"关联的元素定位激活容器,彻底摆脱动态ID的依赖。
  • 等待可交互状态:用element_to_be_clickable替代presence_of_element_located,确保元素处于可操作状态后再执行交互。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:57:47