Home > OS >  Java, Selenium. How to locate a hyperlink WebElement?
Java, Selenium. How to locate a hyperlink WebElement?

Time:01-20

I'm trying to perform a click action on the "sign out" link on Gmail but my console keep saying that it's unable to locate the element. Below is my code.Thank you!

@FindBy(linkText="Sign out")
WebElement logoutLink;

This is the HTML:

enter image description here

And this is the WebElement:

https://i.stack.imgur.com/JI9r6.png

CodePudding user response:

If you observe closely the text Sign out is actually within a <div> which have an ancestor <span> which again have an ancestor <a>

So an effective locator strategy can be:

  • Using xpath:

    @FindBy(xpath="//a//span//div[text()='Sign out']")
    WebElement logoutLink;
    

CodePudding user response:

You can use this XPath to locate that element:

"//a[contains(@href,'Logout')]"

Or this CSS Selector:

"a[href*='Logout']"
  • Related