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

Python-Selenium无法通过ID定位已存在的元素

Fixing the "NoSuchElementException" for Your Readonly Input

Let's break down exactly why your Selenium code is failing and how to fix it:

The Core Problem: Wrong Wait Condition

Your main issue is using EC.element_to_be_clickable() on a readonly input. This expected condition has three strict requirements:

  • Element exists in the DOM
  • Element is visible
  • Element is enabled (not marked as readonly/disabled)

Since your input has the readonly attribute, it will never be "clickable"—so the wait will always time out, causing the TimeoutException. For readonly elements, you need to use a more appropriate wait condition.

Step-by-Step Solutions

1. Wait for the Element to Exist in the DOM

If you just need to locate the element (regardless of visibility or its populated value), use EC.presence_of_element_located():

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, 'submissionKey')))

2. Wait for the Element to Be Visible

If you need to ensure the element is actually visible on the page (not just present in the DOM), use EC.visibility_of_element_located():

element = wait.until(EC.visibility_of_element_located((By.ID, 'submissionKey')))

3. Wait for the JS-Set Value to Be Populated

Since your page uses JavaScript to set the input's value from the auth URL parameter, you might want to wait until the value is actually loaded. Use a custom lambda or the built-in text condition:

# Wait for any non-empty value
element = wait.until(
    lambda driver: driver.find_element(By.ID, 'submissionKey').get_attribute('value') != ''
)

# Or use the built-in condition if you expect a specific value format
element = wait.until(
    EC.text_to_be_present_in_element_value((By.ID, 'submissionKey'), '')
)

Why Your Original find_element_by_id() Failed

The initial NoSuchElementException likely happened because you tried to locate the element before the page's DOM had fully finished rendering. Adding a wait was the right instinct—you just picked the wrong wait condition for a readonly element.

Quick Sanity Checks

  • Double-check your driver is focused on the correct tab/window (no accidental navigation away)
  • Confirm there are no hidden overlays temporarily blocking the element (your HTML doesn't show this, but it's worth ruling out)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:38:16