简体   繁体   中英

Unable to click on multiple links on a webpage in selenium webdriver with java

My Code

WebDriver driver = new FirefoxDriver();
driver.get("https://google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElement(By.name("q")).sendKeys("selenium");
driver.findElement(By.xpath("//button[@value='Search']")).click();

List<WebElement> alllinks = driver.findElements(By.xpath("//div[3][@class='_NId']/div/div/div/h3"));

for(WebElement cl:alllinks)
{
    System.out.println(cl.getText());

    if(cl.getText()!="")
    {
        cl.click();
    }

}

By above code i am not getting any exception but also i am not able to click on any link on a webpage, I just want to click on every link one by one.Please tell me the solution how to do this, Thanks in advance.

Your assumption of opening all links is correct but the code could not show you the desired output as

1> When google results are shown for 'Selenium' keyword, you have many links over there. So if you manually click on every link - it opens in the same tab by which the other links will not be accesible as WebDriver gives you org.openqa.selenium.StaleElementReferenceException: exception.

Now try this code :

        open some driver
        driver.get("https://google.com");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.findElement(By.name("q")).sendKeys("selenium");
        driver.findElement(By.xpath("//button[@value='Search']")).click();

        List<WebElement> alllinks = driver.findElements(By.xpath("//div[3][@class='_NId']/div/div/div/h3"));

        for(WebElement cl:alllinks)
        {
            System.out.println(cl.getText());
            if(cl.getText()!="")
            {
                Actions action = new Actions(driver); // I have added these lines
                action.keyDown(Keys.CONTROL).moveToElement(cl).click().perform();
                action.keyUp(Keys.CONTROL).perform();
            }
         }

So now all links will be opened in a new tab and it works .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM