0

I'm trying to use relative locators in selenium 4, but I'm not having much luck with it.

I found an example here, but even though I'm able to find the first element, the second line doesn't work and it seems to be stuck there (I cannot close the browser automatically afterwards).

decision_div = browser.find_element(By.CLASS_NAME, "decisions")
conclusion_div = browser.find_element(locate_with(By.TAG_NAME,  "div").below(decision_div))

How can I get it to find the next div right below the one with the specified class name?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
mattosmat
  • 610
  • 1
  • 11
  • 27

2 Answers2

0

As you are able to find the first element, I don't see any issues in your code as such:

decision_div = browser.find_element(By.CLASS_NAME, "decisions")
conclusion_div = browser.find_element(locate_with(By.TAG_NAME,  "div").below(decision_div))

You just need to ensure that the the element with the value of class attribute as decisions is above the desired <div> element as follows:

<sometagname class="decisions" ...></div>
<div class="some class" ...></div>

Note : You have to add the following imports :

from selenium.webdriver.support.relative_locator import locate_with

References

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Should I use near instead? As you can see from my screenshot, there are nested divs, but the one I want is inmediately below at the same hierarchy level. – mattosmat Mar 30 '22 at 19:45
  • I would suggest you to raise a new question with your updated requirement as _`locate_with`_ doesn't fits your updated usecase. There are much better ways to deal with nested divs. – undetected Selenium Mar 30 '22 at 19:58
0

Selenium 4 relative locators are dealing with pair of web elements with the similar size and adjacent positions, not what you are trying to do here.
In this case the div element you are trying to locate is similarly nested below the parent element located by decisions class name.
So, you can simply locate the conclusion_div element with this code line:

conclusion_div = browser.find_element(By.XPATH, "//div[@class='decisions']//div")

But since the locator above gives 13 matches and I don't know which of them you want to locate it could be:

conclusion_div = browser.find_element(By.XPATH, "//div[@class='decisions']//div")

Or maybe

conclusion_div = browser.find_element(By.XPATH, "//*[@class='decisions']//div[contains(@class,'carousel')]")

Or maybe

conclusion_div = browser.find_element(By.XPATH, "//*[@class='decisions']//div[@class='decision-image']")
Unused hero
  • 307
  • 1
  • 9