Python Selenium操作screener.in搜索框遇ElementNotInteractableException
解决Selenium操作screener.in搜索框时的ElementNotInteractableException错误
问题原因
- 元素未完全加载:页面渲染未完成就尝试操作,导致元素处于不可交互状态。
- 定位精度不足:页面中可能存在多个class为
u-full-width的input元素,代码定位到的并非目标搜索框。
解决方案
1. 用显式等待替代强制等待
使用WebDriverWait等待元素加载完成并可交互,这比time.sleep更可靠,能避免因加载延迟导致的异常。
2. 优化元素定位规则
结合data-company-search="true"或aria-label="Search for a company"属性定位,确保精准命中目标搜索框。
修改后的代码:
import time 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 driver = webdriver.Chrome() driver.maximize_window() driver.get("https://www.screener.in/explore/") # 显式等待目标搜索框可交互,最长等待10秒 search_box = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//input[@data-company-search='true']")) ) search_box.send_keys("TCS") # 可选:等待搜索结果出现后点击第一个结果进入详情页 # result = WebDriverWait(driver, 10).until( # EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'company-search-result')]//a")) # ) # result.click() time.sleep(100) driver.quit()
额外处理
如果页面存在Cookie同意弹窗,会遮挡搜索框导致操作失败,可提前添加代码处理弹窗:
# 等待Cookie同意按钮并点击(根据页面实际文案调整定位) cookie_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept')]")) ) cookie_btn.click()
内容的提问来源于stack exchange,提问作者Ben Hardy
相关产品推荐
相关产品推荐

