9

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

webElement.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 webElement = driver.findElement(By.linkText("Bicycles"));
        
        System.out.println(webElement.getAttribute("href")); // shows http://bicycles.stackexchange.com/
        System.out.println(webElement.getAttribute("linkText")); // shows null

4 Answers 4

6

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

String text = element.getAttribute("innerHTML")
Sign up to request clarification or add additional context in comments.

1 Comment

Usually, the link text value goes together with unnecessary carriage return symbols and whitespaces. it's better to trim them all like this: String text = element.getAttribute("innerHTML").replaceAll("\\p{Cntrl}", "").trim();
4

Try this:

System.out.println(link.getText());

Comments

1

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

1 Comment

<a> or anchor tag a.k.a hyperlink is not block level element, it's inline element
1

Here you can store your id text:

String text = driver.findElement(By.id("Text")).getText();
System.out.println(text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.