Home > OS >  How can I iterate through the hover pictures and click on every profile under the them?
How can I iterate through the hover pictures and click on every profile under the them?

Time:09-21

I'm on the https://the-internet.herokuapp.com/hovers . I would like to create a for loop, that moves the mouse cursor to the pictures, clicks on the profile links, then navigates back to the pictures and clicks on the next pictures, etc.

private final By images = By.xpath("//*[@class=\"figure\"]"); 
private final By profileLinks = By.xpath(".//div/a"); // relative xpath    
public void clickAllProfiles() 
{
        Actions actions = new Actions(driver);
        List<WebElement> pictures = driver.findElements(images);   
        for (WebElement pic : pictures)     
        {
            actions.moveToElement(pic)
                    .click(driver.findElement(profileLinks))
                    .build()
                    .perform();
            driver.navigate().back();
            System.out.println(driver.getCurrentUrl());
        }
}

I don't know why, but my test automation does not click on the links under the pictures, and navigates back to the main page.

CodePudding user response:

Try this code, this is working.

    List<WebElement> pictures = driver.findElements(By.xpath(".//img[@alt='User Avatar']"));
    
    Actions actions = new Actions(driver);
    int i = 1;
    for (WebElement pic : pictures) {
        actions.moveToElement(pic).click(driver.findElement(By.xpath(".//a[@href='/users/"   i   "']"))).perform();
        Thread.sleep(1000);
        driver.navigate().back();
        i  ;
    }
        
  • Related