0

I'm trying to get an access to div.y element.

<div class="x">
  <div class="y"></div>
</div>

I know that I can directly get the div.y element using Selenium in Python.

But is it possible to call the functions like this?

browser.find_element_by_class_name("x").find_element_by_class_name("y")

Does the code above find div.y element only within the div.x element?

Justin M
  • 177
  • 1
  • 3
  • 11
  • Yes. But why do you ask that? Just try it out by yourself. Or does it not work for you? – Sven Eberth Jun 15 '21 at 00:03
  • @Sven Eberth I actually did. But seems like there's no one calling the find_element_by_ functions like that so I wonder if there is a good reason that people don't do that way. – Justin M Jun 15 '21 at 00:09
  • Okay. sometimes things are technically possible, but not particularly efficient or smart. The alternatives mentioned by C. Peck are therefore to be preferred. But other solutions work too :) – Sven Eberth Jun 15 '21 at 00:20

1 Answers1

1

I'm not sure why you don't just try it, but yes, you can do so and it works as you probably expect. That is, it will find the first element with class y that is a descendant of the first x element on the page.

C. Peck
  • 3,641
  • 3
  • 19
  • 36
  • I have tried it and worked as I expected. But I've never seen other people do like that so I thought there must be some other reasons that I am not aware of. – Justin M Jun 15 '21 at 00:06
  • you can normally combine it into one xpath or css selector. For example I believe `browser.find_element_by_class_name("x").find_element_by_class_name("y")` is equivalent to `browser.find_element_by_css_selector(".x .y")` – C. Peck Jun 15 '21 at 00:09
  • I think the biggest usecase for `WebElement.find_element()` is when you are iterating through a list to find elements, like `for outerdiv in outerdivs: outerdiv.find_element().click()` – C. Peck Jun 15 '21 at 00:12