How to get Xpath with selenium

Question:

I have a list of elements after using find_elements method. The list contains soemthing like this

<selenium.webdriver.remote.webelement.WebElement (session="b816a8a89e827bd47f5d2c7e66169c67", element="ed2cb578-6222-41cc-ab44-d3e183f48935")>

Is there a way to get the Xpath of each one from something like session or element which I think is unique, because I need to access each one’s child and parent?

alist = list
sleep(5)
for session in alist:
    self.Name = session.find_element('xpath', '//a[contains(@href, "student")]').text
    print(self.Name)

Example of element containing child in a table:

<tr style="border-bottom:2px solid black !important;">
    <td>
      <div>
        <a href="http://bequran.uk/student/profile/2032">Name</a>
      </div>
    </td>
</tr>
Asked By: Omar Yacop

||

Answers:

If you found WebElement with find_elements/find_element you can select its child/parent with XPath or other locator types e.g.

element = driver.find_element(...)
parent = element.find_element('xpath', './parent::*')
child = element.find_element('class name', 'some_class_name')

Update

If you want to select child of element you need to specify context node (note the leading .):

session.find_element('xpath', './/a[contains(@href, "student")]').text
Answered By: Curious koala
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.