Selenium - 如何在 WebDriver 中通过 href 值单击链接

标签 selenium xpath onclick css-selectors webdriverwait

我有这段代码

<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 事件WebElementJavaScript启用的元素。因此,要在元素上调用 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/

相关文章:

C# XPATH 选择子节点内部文本所在的属性

javascript - 使用 jQuery 到 'click' 一个 li 元素

javascript - jquery 单击事件不适用于动态字段

testing - 如果不满足测试先决条件,则抛出异常或 Assert.Fail

xml - XQuery:如何使用内部 for 循环的结果来对外部 for 循环的结果进行排序?

java - Selenium IE 驱动程序找不到新打开的窗口

regex - 从 Jmeter 的站点地图中替换 ${url} 的一部分

javascript - 单击事件在表中被触发两次

xml - 无法使用 xpath == "//*[text()[contains(.,' "+ word + " ')]]"找到元素

python - 在 selenium python webdriver 中,我无法下载扩展名为 .lst 的文本文件