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

使用Expected Conditions仍遇Selenium元素不可交互异常求助

问题分析与解决方案

出现ElementNotInteractableException核心原因如下:

  • 定位对象错误:你使用的//*[@id="heroSearchContainer"]是搜索栏的外层容器(div元素),并非真正可输入的<input>标签,容器本身无法接收输入操作。
  • 等待时长不足:3秒等待时间可能不足以让页面动态元素完全渲染完成。
  • 元素未在视口内:部分场景下元素可能处于页面不可见区域,导致无法触发交互。

具体修复步骤

  1. 修正元素定位
    替换搜索栏的xpath为真正的输入框元素,Trustpilot首页搜索input的准确xpath为://*[@id="heroSearchContainer"]//input[@type="search"]

  2. 延长等待时间
    将WebDriverWait超时时间从3秒调整为10秒,确保元素有足够加载时长。

  3. 添加视口滚动操作
    操作前将元素滚动到当前可见区域,避免因元素不可见导致交互失败。

  4. 优化cookie操作后的等待
    点击cookie按钮后,等待弹窗完全消失再执行搜索操作。

修改后的代码

Scraper类初始化修改:

class Scraper:
    def __init__(self):
        _edge_driver = os.path.join(os.getcwd(), 'msedgedriver.exe') #path to the edge driver
        options = EdgeOptions()
        options.add_argument('start-maximized')
        self.driver = webdriver.Edge(executable_path=_edge_driver, options= options)
        self.wait = WebDriverWait(self.driver,10) # 延长等待时间至10秒

search_bar方法修改:

def search_bar(self, search: str, xpath: str):
        """
        Looks for the search bar on the website and sends the search string

        Input: 
            search (str)
                the string to be search on
            xpath (str)
                the value of the xpath where the search is located
        

        """
        search_bar = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
        # 将元素滚动到视口内
        self.driver.execute_script("arguments[0].scrollIntoView(true);", search_bar)
        # 等待元素可点击
        self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
        
        search_bar.click()
        search_bar.send_keys(search)
        search_bar.send_keys(Keys.RETURN)

调用代码修改:

scraper = Scraper()
scraper.load_webpage('https://uk.trustpilot.com/')
scraper.click_on_cookie('//*[@id="onetrust-accept-btn-handler"]')
# 等待cookie弹窗消失
scraper.wait.until(EC.invisibility_of_element_located((By.ID, "onetrust-banner-sdk")))
# 使用修正后的输入框xpath
scraper.search_bar('travel insurance', '//*[@id="heroSearchContainer"]//input[@type="search"]')

备选方案(若仍有问题)

可以尝试用ActionChains模拟手动操作,替代直接的click()和send_keys():

from selenium.webdriver.common.action_chains import ActionChains

# 在search_bar方法中替换点击输入逻辑
actions = ActionChains(self.driver)
actions.move_to_element(search_bar).click().send_keys(search).send_keys(Keys.RETURN).perform()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:50:33