Michal Michal - 4 months ago 19
HTML Question

Get link text Selenium java

I have problem with getting text of link.

On site I have text link

<a href="DetailsZZ-10048.html">ZZ-10048</a>
, part with
ZZ-
is static, the number increments and it isn't known for me earlier. I need to get this number.

I used looking at: Get link text - Selenium, Java but there I have all links, URLs (not the text of the links)

I also tried: How to gettext() of an element in Selenium Webdriver but I get on output
Printing null
everytime I changed and looked for a solution

And the solution: Java Selenium, how to get linkText (anchor) from link WebElement is not good also, because it doesn't recognise
"a[href*='ZZ-']"


So, the closest one is:

List<WebElement> elements = driver.findElements(By.tagName("a"));
for (int i = 0; i < elements.size(); i++) {
System.out.println(elements.get(i).getAttribute("href"));
}


but how can I change to view not only URLs, but names of the link? (especially one which starts from
ZZ-
)

Answer

Hi you can use the following code to extract the number :

public String splitfunc(String str)
{
    str = str.replace(".html", "");
    String[] array = str.split("-"); 
    return array[1];
}


  List<WebElement> elements = driver.findElements(By.tagName("a")); 
  for (int i = 0; i < elements.size(); i++) {
   System.out.println(splitfunc(elements.get(i).getAttribute("href")));
}
Comments