Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find nested elements by class in Selenium

I have a div inside a div inside another div. Most outer div class is "Big Div", inside it there is a div with class "Medium Div" and the most inner div class is "Small Div".

I'm able to see the div's classes when I press the F12 key and hover over the elements, however I can't find them using Selenium.

What am I doing wrong?

WebElement big = browser.findElement(By.cssSelector("//div[contains(@class,'Big')]"));
WebElement medium = big.findElement(By.cssSelector("//div[contains(@class,'Medium')"));
WebElement small = medium.findElement(By.cssSelector("//div[contains(@class,'Small'"));

Note: my classes contain white spaces, Selenium can't find any of the divs and I get the exception: "No Such element".

like image 308
Tal Angel Avatar asked Dec 06 '22 09:12

Tal Angel


1 Answers

The syntax you have used that is not for cssSelector that for XPATH and you have missed parenthesis as well.

Try following xpath now.

WebElement big = browser.findElement(By.xpath("//div[contains(@class,'Big')]"));
WebElement medium = big.findElement(By.xpath(".//div[contains(@class,'Medium')]"));
WebElement small = medium.findElement(By.xpath(".//div[contains(@class,'Small')]"));

However you can do it in once like.

WebElement small = browser.findElement(By.xpath("//div[contains(@class,'Big')]//div[contains(@class,'Medium')]//div[contains(@class,'Small')]"));
like image 89
KunduK Avatar answered Dec 21 '22 09:12

KunduK