Chrome Selenium点击不总是有效

yb3bgrhw  于 2023-02-01  发布在  Go
关注(0)|答案(5)|浏览(124)

我有一些点击选项卡的测试,但并不总是执行点击。

  • xpath是正确的,因为大多数时候测试都有效
  • 这不是一个计时问题,因为我已经使用thread.sleep()和其他方法来确保元素在单击之前可见
  • 测试认为它正在执行单击,因为它在“执行”单击时没有引发ElementNotFoundException或任何其他异常。测试在单击后失败,因为选项卡内容不会更改。

更多信息我正在使用Selenium 2.44.0在Java中实现测试,该测试在Chrome 44.0.2403.107 m上运行。
我还能做些什么吗?或者这可能是 selenium 的问题?

nhaq1z21

nhaq1z211#

您可以尝试以下几种方法:

  • 显式elementToBeClickable等待:
WebDriverWait wait = new WebDriverWait(webDriver, 10);

WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("myid")));
button.click()
  • 单击前移动到元素:
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
  • 通过javascript进行点击:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", button);
p5fdfcr1

p5fdfcr12#

如果选项卡名称包含任何唯一的字符串,你可以使用linkText。2并且确保你的选项卡不是动态的。3它应该在源代码中可见(手动源代码(ctrl+u))。

ukxgm1gy

ukxgm1gy3#

以下方法对我有效

WebElement button = SeleniumTools.findVisibleElement(By.cssSelector("#cssid"));

Actions actions = new Actions(driver);

actions.moveToElement(button).click().build().perform();
nwlls2ji

nwlls2ji4#

我也有类似的问题。试过上面答案的所有解决方案。有时有效,有时无效。
但是在无限循环中运行代码总是有效的。
例如,我们需要单击element-two,在单击element-one之前,element-two是不可见的。

WebDriverWait wait = new WebDriverWait(webDriver, 10);
while (true){
    try {
        WebElement elementOne = 
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-one")));
        elementOne.click();
        WebElement elementTwo = 
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-two")));
        elementTwo.click();
        break;
    } catch (Exception e){
        //log
    }

}
50few1ms

50few1ms5#

我也有类似的问题,下面是我的解决方案:

table_button = driver.find_element(By.XPATH, insert your xpath)
try:
    WebDriverWait(driver, 15).until(EC.element_to_be_clickable(table_button)).click()
except WebDriverException as e:
    print('failed')
    print(e)

通过上面的代码,如果您的按钮不可点击,您可以找到错误消息。
例如,我的错误消息是“nosuchelement”和“clcik is not clickable”,然后我回去检查table_button.accessible_name,发现它打印了一个“null”值,这意味着我的XPATH不正确。

相关问题