Selenium - How to Click a Link by href value in WebDriver

I have this piece of code

<a href="/iot/apply/device.do" id="subMenu1" class="fortification55"
                                                        onclick="$('#deviceinfo').hide()">Apply</a>

I am trying to link by href using

getDriver().findElement(By.name("subMenu1")).click();

But i got this error

org.openqa.selenium.NoSuchElementException: Unable to find element with name == subMenu1 (WARNING: The server did not provide any stacktrace information)

Upvotes: 2

Views: 8169

Answers (2)

QA Square
QA Square

Reputation: 253

the following code should work :

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

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193088

As the element is having the onclick Event, the WebElement is a JavaScript enabled element. So to invoke click() on the element you need to use WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • Using cssSelector and only href attribute:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/iot/apply/device.do']"))).click();
    
  • Using xpath and only href attribute:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/iot/apply/device.do' and text()='Apply']"))).click();
    
  • Using a canonical cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.fortification55#subMenu1[href='/iot/apply/device.do']"))).click();
    
  • Using a canonical 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();
    
  • Note : You have to add the following imports :

    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.By;
    

References

You can find a couple of relevant discussions on NoSuchElementException in:

Upvotes: 3

Related Questions