2

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

1
  • you can try to find text for a link By.xpath: //a[contains(href, "DetailsZZ-")] Commented Feb 29, 2016 at 9:28

7 Answers 7

4

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")));
}
Sign up to request clarification or add additional context in comments.

4 Comments

works almost great, I think I know what you want to show :) I just got "java.lang.ArrayIndexOutOfBoundsException: 1" error on the return, so I just need to find out what's happend (but thanks for a rod :) )
@Michal : I am guessing there are some a element(s) without the numerical value in their href attribute; something like: "DetailsZZ" or "DetailsZZ-" or "<some other random text>", and that's why it throws ArrayOutOfBoundsException since there is no second value in the array to display. Try in the above code, as @Andersson commented, by replacing with either of these List<WebElement> elements = driver.findElements(By.xpath("//a[contains(@href, "DetailsZZ-")]")); or List<WebElement> elements = driver.findElements(By.xpath("//a[starts-with(href, "DetailsZZ-")]"));
You guys are great, that's what it should do! :D Thank you! But for the future if somebody will look here, it should be 'DetailsZZ-' instead of "DetailsZZ-" :)
@Michael....thats sounds an array problem to me i.e Array[1]...it may happen when the value does not exist for an array and we trying to fetch it..
1

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];
}

2 Comments

it works almost great, I just get the NullPointerException on the String[] data = text.split("-"); line, so I'm making to find out what's happens :)
@Michal with both versions of text extracting?
0

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.

Comments

0

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

Comments

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

1 Comment

I am not sure, but element.element.getText() should not compile because element is not a public field in WebElement.
0

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.

1 Comment

This will not compile.
-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());

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.