Search code examples
javaseleniumselenium-webdriverhttpconnection

How to Handle Links with Blank Targets in Selenium Web driver


I was checking for the active links on the page..using htttpurlconnection.

I came across one situation.

U can see some links with target="_blank"

I do not want to include such links to the linkedlist. I tried to exclude the same using getattribute property of target.But it is not working.

!https://i.sstatic.net/ICJS3.jpg

List <WebElement> activelinks = new ArrayList<WebElement>();

for (int i=0;i<linkslist.size();i++) {

    system.out.println("link address of full links and images>>> " +  linkslist.get(i).getAttribute("href")); 

    if (linkslist.get(i).getAttribute("href")!=null && (linkslist.get(i).getAttribute("target")!="_blank" )) {
        activelinks.add(linkslist.get(i));
        System.out.println("active link " + 
        activelinks.get(i).getAttribute("href"));
    }
}

Solution

  • The easiest option is performing filtering on XPath selector level, if you want to match links which:

    • have href attribute

    and

    • have target attribute not equal to _blank

    You can match such links as simple as:

    //a[@href and not(@target='_blank')]
    

    With regards to your approach, you should be using String.equals() method for comparison, suggested code would be:

    List<WebElement> activeLinks = linkslist
            .stream()
            .filter(link -> link.getAttribute("href") != null)
            .filter(link -> !link.getAttribute("target").equals("_blank"))
            .collect(Collectors.toList());