Michal
Michal

Reputation: 464

Get link text using Selenium and Java

I have a problem with getting the text of a link.

On a site, I have the text link <a href="DetailsZZ-10048.html">ZZ-10048</a>. The 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 got output Printing null every time I changed and looked for a solution.

And the solution: Java Selenium, how to get linkText (anchor) from link WebElement is not good either, 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-)

Upvotes: 2

Views: 14199

Answers (7)

Ankur Gupta
Ankur Gupta

Reputation: 123

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")));
}

Upvotes: 4

cruisepandey
cruisepandey

Reputation: 29362

There exact solution of this problem would be something like :

As you have mentioned you want to get the number after -

For that, you can use start-with which is available in xpath for matching the start text.

 List<WebElement> elements = driver.findElements(By.xpath("//a[starts-with(text(),'ZZ-')]")); 
  for (int i = 0; i < elements.size(); i++) {
   System.out.println(elements.get(i).getAttribute("href")));  

@Gupta answer is good hack though. IMO , it was not the proper solution regarding selenium.

Upvotes: 0

Suraj Choudhary
Suraj Choudhary

Reputation: 1

I think this is one of the simplest ways to fetch text, available from an anchor.

WebElement link  = driver.findElement(By.partialLinkText("ZZ"));
System.out.println(link.getText());

Upvotes: -1

K.Krishnakanth
K.Krishnakanth

Reputation: 127

WebElement element = driver.findElement(By.partialLinkText("ZZ-10048"));
String txt = element.getText();
String[] words = txt.split("-");
System.out.println(words[1]);

Upvotes: 0

robx
robx

Reputation: 3123

A more elegant way to get it without risk of index out of bounds exception is to use a foreach if your language level allows.

This will allow you to get the text of the link as you requested, and not the href and do so much parsing.

The trim is just extra defensive coding.

List<WebElement> links = driver.findElements(By.tagName("a")); 
for (WebElement link : links ) {
   System.out.println(link.getText().replace("ZZ-","").trim());
}

Upvotes: 0

Aaron Davis
Aaron Davis

Reputation: 1731

Since you are looking for the text of the link and not the actual href URL itself, I think it is cleaner and less error prone to grab the element text and use that for parsing rather than pulling out the href attribute. Then, if the text is always in the form of ZZ-someNumber then you can make the parsing fairly simple.

Example using Java 8 (assuming the driver has already been created and has loaded the correct page):

String leadingStr = "ZZ-";
List< Integer > numbers = driver.findElements(By.tagName("a"))
                                .stream()
                                .map(WebElement::getText)
                                .filter(str -> null != str && str.startsWith(leadingStr))
                                .map(str -> str.replace(leadingStr,"").trim())
                                .filter(str -> !str.isEmpty())
                                .map(Integer::valueOf)
                                .collect(Collectors.toList());

Example without streams:

String leadingStr = "ZZ-";
List< Integer > numbers = new ArrayList<>();
for (WebElement elem : driver.findElements(By.tagName("a"))) {
    String text = elem.getText();
    if (text.startsWith(leadingStr)) {
        numbers.add(Integer.valueOf(text.replace(leadingStr,"").trim()));
    }
}

Of course both of the above would need a bit more error handling if the assumption that they are always in the form of ZZ-someNumber isn't valid but then it is just a simple addition of some try catch blocks around the integer conversion, etc.

Upvotes: 0

Guy
Guy

Reputation: 50809

To locate the element you can use

List<WebElement> elements = driver.findElements(By.partialLinkText("ZZ"));
// or
List<WebElement> elements = driver.findElements(By.cssSelector("[href*='ZZ']"));

To get the href and text you can do

for (WebElement element : elements) {
    String href = element.getAttribute("href");
    String text = element.getText();
    // or
    String text = element.getAttribute("innerText");

    // and to get the number
    String[] data = text.split("-");
    String number = data[1];
}

Upvotes: 1

Related Questions