Selenium中Keys.ENTER在'title-input'元素上失效求助
Hey there! Sorry to hear you're stuck with sending the Enter key via Selenium—let's work through this together. You already confirmed you're targeting the right title-input element and tried both ENTER and RETURN keys, so let's dive into actionable fixes and checks that often resolve this kind of problem:
Wait for full interactability first
Even if you can locate the element, it might not be fully ready to accept input. Try using an explicit wait to ensure it's clickable before sending keys: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.common.keys import Keys wait = WebDriverWait(driver, 10) title_input = wait.until(EC.element_to_be_clickable((By.ID, 'title-input'))) title_input.send_keys(Keys.ENTER)(Swap out
By.IDfor your actual locator type if needed, likeBy.CSS_SELECTOR)Bypass with JavaScript execution
Sometimes Selenium's native key simulation doesn't trigger custom event listeners on elements. Try firing the Enter key press directly via JS:driver.execute_script(""" const input = document.getElementById('title-input'); const enterEvent = new KeyboardEvent('keypress', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true }); input.dispatchEvent(enterEvent); """)Ensure the element is focused first
Some inputs require explicit focus before key presses register. Try clicking the element first, then sending the key:title_input = driver.find_element(By.ID, 'title-input') title_input.click() title_input.send_keys(Keys.ENTER)Or confirm focus is set with:
wait.until(EC.element_to_be_clickable((By.ID, 'title-input'))).click() driver.switch_to.active_element.send_keys(Keys.ENTER)Check if the action ties to a submit button
Pressing Enter might be supposed to trigger a hidden or adjacent submit button, not the input itself. Try locating and clicking that button instead:# Look for a submit button (adjust selector as needed) submit_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]') submit_btn.click() # If it's hidden, use JS to click it driver.execute_script("document.querySelector('button[type=\"submit\"]').click();")Verify you're not in an iframe
If thetitle-inputis inside an iframe, you'll need to switch to that frame first before interacting with it:# Switch to the iframe (use your iframe's locator) driver.switch_to.frame(driver.find_element(By.ID, 'target-iframe')) # Now interact with title-input # Don't forget to switch back when done! driver.switch_to.default_content()
Since you mentioned you've already tried multiple methods, sharing the specific code snippets of those attempts and the full outerHTML of the title-input element would help us narrow this down even more. For example, dynamic attributes like readonly or disabled (even added after page load) could block key presses.
内容的提问来源于stack exchange,提问作者Shahar Azar

