首页 > 解决方案 > 单击不适用于 Selenium 的元素

问题描述

我正在尝试使用 Selenium 单击一个元素。它是一个带有以下 HTML 代码的复选框:

尝试单击复选框以获取条款

包含复选框和条款的段落代码:

<p class="jss72 jss80 jss927 jss943 jss930">
    <span class="js122">
        <img src="/images/purple.svg">
    </span>
    <span class="jss941">
        I Agree To The Terms
    </span>
</p>

我尝试了三种不同的方法,但都没有奏效:

//Tried with xpath clicking on image: Error: Element not interactable   
driver.FindElement(By.XPath("//img[@src='/images/purple.svg']")).Click();

//Tried with Xpath by selecting the span 
driver.FindElement(By.XPath("//span[@class='js122')]")).Click();

//Tried with CssSelector Error: Element not interactable  
driver.FindElement(By.CssSelector("img[src*='purple.svg']")).Click();

请帮助解决任何其他问题。

标签: c#selenium

解决方案


ElementNotInteractableException 是由于 Selenium 执行代码和浏览器在页面上执行 JavaScript 之间的竞争条件而发生的。您要单击的元素存在于天桥中。我敢打赌,天桥出现时会出现淡入动画。有一个短暂的时刻,您可以明显地看到复选框,Selenium 可以在 DOM 中找到它,但 Selenium 无法单击它。解决方案非常简单。使用显式等待:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

// The 'd' parameter to the lambda expression is an IWebDriver object
wait.Until(d => d.FindElement(By.XPath("//img[@src='/images/purple.svg']")).Click());

推荐阅读