Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Selenium, how to get linkText (anchor) from link WebElement

I have a WebElement containing link found by url. I can extract url by:

element.getAttribute("href");

But the question is: how to extract it's anchor, I'm trying like this:

webElement.getAttribute("linkText");

It gives me null value. I'm 100% sure this link has an anchor. Is there any way to get anchor ? It's more complicated, but example simplified code could look like this:

WebDriver driver = new FirefoxDriver();
        driver.get("http://stackoverflow.com/questions/tagged/java");
        WebElement link  = driver.findElement(By.linkText("Bicycles"));

        System.out.println(link.getAttribute("href")); // shows http://bicycles.stackexchange.com/
        System.out.println(link.getAttribute("linkText")); // shows null
like image 766
RichardK Avatar asked Apr 22 '15 12:04

RichardK


People also ask

How do I find the anchor tag in Selenium?

A linkText is used to identify the hyperlinks on a web page. It can be determined with the help of an anchor tag (<a>). In order to create the hyperlinks on a web page, you can use anchor tags followed by the linkText.

How do I find the text in an element with a link?

We can find an element using the link text or the partial link text in Selenium webdriver. Both these locators can only be applied to elements with the anchor tag. The link text locator matches the text inside the anchor tag. The partial link text locator matches the text inside the anchor tag partially.

How does Selenium find element by link?

Using Link Text In Selenium To Locate An Element In order to access link using link text in Selenium, the below-referenced code is used: driver. findElement(By. linkText("this is a link text"));


3 Answers

If getText() returns an empty String, try the innerHTML attribute:

String text = element.getAttribute("innerHTML")
like image 157
Jonas_Hess Avatar answered Oct 11 '22 19:10

Jonas_Hess


Try this:

System.out.println(link.getText());
like image 28
nalini Avatar answered Oct 11 '22 20:10

nalini


By "Anchor" I think you mean the text of the link? If so, then you can use .getText() since an <a> is a block level element.

link.getText();
like image 22
ddavison Avatar answered Oct 11 '22 21:10

ddavison