我有这段代码
<a href="/iot/apply/device.do" id="subMenu1" class="fortification55"
onclick="$('#deviceinfo').hide()">Apply</a>
我正在尝试使用 href 进行链接
getDriver().findElement(By.name("subMenu1")).click();
但是我收到了这个错误
org.openqa.selenium.NoSuchElementException: Unable to find element with name == subMenu1 (WARNING: The server did not provide any stacktrace information)
最佳答案
由于该元素具有 onclick 事件,WebElement是 JavaScript启用的元素。因此,要在元素上调用 click()
,您需要使用 WebDriverWait对于 elementToBeClickable()
,您可以使用以下任一 Locator Strategies :
使用 cssSelector 和仅 href 属性:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/iot/apply/device.do']"))).click();
使用 xpath 和仅 href 属性:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/iot/apply/device.do' and text()='Apply']"))).click();
使用规范的 cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.fortification55#subMenu1[href='/iot/apply/device.do']"))).click();
使用规范的xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='fortification55' and @id='subMenu1'][@href='/iot/apply/device.do' and text()='Apply']"))).click();
注意:您必须添加以下导入:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.By;
引用文献
您可以在以下位置找到一些关于 NoSuchElementException 的相关讨论:
关于Selenium - 如何在 WebDriver 中通过 href 值单击链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078922/