首页 > 解决方案 > 找到 Selenium 按钮但未执行单击

问题描述

我想单击由 xpath 标识的按钮,但它不起作用。

但是,单击操作没有错误。找到按钮,但未执行单击操作。

我尝试了以下解决方案:

解决方案 1

WebElement elem = driver.findElement(By.xpath("//button[@id='btn_M9pg_']"));
Actions actions = new Actions(driver);
actions.moveToElement(elem);
actions.click(elem);
Action a = actions.build();
a.perform();

解决方案 2

driver.findElement(By.xpath("//button[@id='btn_M9pg_']")).click();

你能帮我吗?非常感谢!

更新 1

请在日志下方找到。btn_D_Ir_未找到按 id 的元素按钮,因为//button[@id='btn_M9pg_']未执行上一次单击 ( )。

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.id: btn_D_Ir_ (tried for 30 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at TripleA.TFT_508.main(TFT_508.java:219)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#btn_D_Ir_"}
  (Session info: chrome=78.0.3904.87)

标签: javaseleniumselenium-webdriverselenium-chromedriver

解决方案


You can try use WebDriverWait, like this:

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='btn_M9pg_']"))).click();

And you can click via js, like this:

WebElement element = driver.findElement(By.id("btn_M9pg_")); 
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

推荐阅读