Home > Back-end >  How to access to non unique subclass of every element during iteration with Selenium?
How to access to non unique subclass of every element during iteration with Selenium?

Time:11-05

I am iterating through elements on the website with XPath of each element.

//*[@id="app"]/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div[X]

X values: from 1 to n. Where X is an ordinal number of the element.

xpath.getText() give me the name and price of current item. I want to download the image also. Class name for the image isn't unique. It same for every element: "shop-card__image-block".

How to access"shop-card__image-block" for every element? I want to take the link to the image and download it with the name and price.

See the images.

First image

Second image

CodePudding user response:

Use element.findElement(By by) or element.findElements(By by) to get child element(s). See https://www.tutorialspoint.com/locating-child-nodes-of-webelements-in-selenium.

CodePudding user response:

Code :

WebDriverWait wait = new WebDriverWait(driver, 30);
int divSize = driver.findElements(By.xpath("//*[@id='app']/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div")).size();

for (int i = 1; i<= divSize; i  ) {
    WebElement parentDiv = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='app']/div[1]/main/div[2]/section/div/section/div[4]/div[1]/div['" i "']")));
    WebElement image = parentDiv.findElement(By.xpath(".//descendant::div[contains(@class,'shop-card__image-block')]"));
    
    // now image is a web element, you can perform a click on it like image.click(); or any other operation. 
}

now image is a web element, you can perform a click on it like image.click(); or any other operation.

trust this helps.

  • Related