Home > Enterprise >  How to use locate_with in selenium 4
How to use locate_with in selenium 4

Time:03-31

I'm trying to use enter image description here

I want to get the ng-binding ng-scope class element. I just fear there might be another such element on the website and that's why I wanted to use relative locators.

CodePudding user response:

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  ...></div>
<div  ...></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:

CodePudding user response:

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']")
  • Related