【问题标题】:Selenium - How to Click a Link by href value in WebDriverSelenium - 如何通过 WebDriver 中的 href 值单击链接
【发布时间】:2016-12-28 23:15:10
【问题描述】:

我有这段代码

<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)

【问题讨论】:

  • 我认为你应该使用By.id("subMenu1")
  • 也可以直接使用getDriver().findElement(By.linkText("Apply")).click();
  • 你也可以使用xpaths://a[@id='subMenu1']//a[text()='Apply']
  • 您可以用作:getDriver().findElement(By.className("fortification55")).click();

标签: selenium xpath onclick css-selectors webdriverwait


【解决方案1】:

由于元素具有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 的几个相关讨论:

【讨论】:

  • @nice 答案应该可以解决这个问题,很好的解释做得好
【解决方案2】:

以下代码应该可以工作:

By.xpath("//a[@href='/iot/apply/device.do']")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多