Home > Software engineering >  Python Selenium get parent element
Python Selenium get parent element

Time:11-26

My html code looks like:

<li>
  <div class="level1">
    <div id="li_hw2" class="toggle open" </div>
  <ul style="" mw="220">
    <li>
      <div class ="level2">
        ...
    </li>
  </ul>

I am currently on the element with the id = "li_hw2", which was found by

level_1_elem = self.driver.find_element(By.ID, "li_hw2")

Now i want to go from level_1_elem to class = "level2". Is it possible to go to the parent li and than to level2? Maybe with xpath? Hint: It is neccassary to go via the parent li and not directly to the element level2 with

self.driver.find_element(By.Class_Name, "level2")

CodePudding user response:

The best-suited locator for your usecase is xpath, since you want to traverse upward as well as downwards in the HTMLDOM.

level_1_elem = self.driver.find_element(By.XPATH, "//div[@class='li_hw2']")

and then using level_1_elem web element, You can do the following :

  1. to directly go to following-sibling

    level_1_elem.find_element(By.XPATH, ".//following-sibling::ul/descendant::div[@class='level2']")
    

CodePudding user response:

Are you sure about the html i think the ul should group all the li if it s the case then it s easy if not i realy dont get that html.

//div[@]/parent::li/parent::ul/li/div[@class="level2"]
  • Related