Home > database >  While opening links in reverse order in new tabs, I want to exclude "sports" and "IR&
While opening links in reverse order in new tabs, I want to exclude "sports" and "IR&

Time:03-11

I want to open links from contents from bottom to top in new tab:

driver.get("https://en.wikipedia.org/wiki/Sports_video_game");
        WebElement contents = driver.findElement(By.xpath("//*[@id='toc']"));
        List<WebElement> links = contents.findElements(By.tagName("a"));
        String clickonlinkTab=Keys.chord(Keys.CONTROL, Keys.ENTER);
         for(int i = links.size() - 1; i >= 0; i--)
{
links.get(i).sendKeys(clickonlinkTab);
links.findElement(By.partialLinkText("sports")).notclick();
links.findElement(By.partialLinkText("IR")).notclick();
}

I want Selenium to skip links which has "sports" and "IR" any where on it.

CodePudding user response:

As "notclick" is not a valid method, the simplest solution is to check if the link text contains "Sports" or "IR" before performing the click action. E.g:

for (int i = links.size() - 1; i >= 0; i--) {
    if (!(links.get(i).getText().toLowerCase().contains("sports")
        || links.get(i).getText().toLowerCase().contains("ir"))) {
        links.get(i).sendKeys(clickonlinkTab);
    }
}

Here is a link to a runnable test case where you can see the results, including printing to verify that it works. If you want to edit, making an account can be done for free via the edit button.

  • Related