Home > Blockchain >  Is there a way to identify a web element selenium using an already identified element?
Is there a way to identify a web element selenium using an already identified element?

Time:11-10

I have an element identified using python selenium.

Below is the code:

driver.get("https://stackoverflow.com/")
element = driver.find_element(By.XPATH, "//a[@])

Is there a way to identify a web element in python selenium using an already identified element? using any method possible. A child element, or a sibling element. It could be using xpath, css_selector, or any way. Above is just an example code, and have used xpath only for example purpose.

CodePudding user response:

We can find child element based on parent element instance and some child element attributes similarly to how we locating regular element. This can be done both with XPath and CSS Selectors.
For example, let's say the child element is div with id=child.
Locating this element with XPath will be as following:

driver.get("https://stackoverflow.com/")
parent_element = driver.find_element(By.XPATH, "//a[@class='s-topbar--logo js-gps-track']")
child_element = parent_element.find_element(By.XPATH, ".//div[@id='child']")

The only 2 important changes here are:

  1. We apply find_element method on parent_element object, not on the driver object.
  2. The XPath is starting with a dot . to make the XPath relative to the current node.

See here how to do that with CSS Selectors or here for more explanations about XPath relative locators.

  • Related