javaseleniumselenium-webdriver

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


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

Solution

  • Try this:

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