1

Take this simple code:

<! DOCTYPE html>
<html>
<body>

<div id="001">
    <div title="hi">hi</div>

</div>

</body>
</html>

How can I find the id "001" by knowing the title "hi" with this:

driver.find_elements_by_xpath("//*[@title='hi']")

I've already seen this: Select parent element of known element in Selenium but it doesn't work on Python

Community
  • 1
  • 1
Matteo Secco
  • 613
  • 4
  • 10
  • 19
  • What do you mean by, "it doesn't work on Python"? – Mark Lapierre Mar 22 '17 at 15:11
  • Did you try `child_element = driver.find_elements_by_xpath("//*[@title='hi']")` and then `parent_elem = child_element.find_elements_by_xpath('..')` Now to fetch the id simply do `parent_elem.get_attribute('id')` – Jayesh Doolani Mar 22 '17 at 15:15
  • @JayeshDoolani yes, but it says that *list* does not have *.find_elements_by_xpath* attribute. My code is: *elem = driver.find_elements_by_xpath("//*[@title='"+team+"']")* *padre = elem.find_elements_by_xpath('..')* – Matteo Secco Mar 22 '17 at 15:29
  • change the `find_elements_by_xpath` to `find_element_by_xpath` – Jayesh Doolani Mar 22 '17 at 15:32

1 Answers1

4

First fetch the child <div> element which has the attribute title='hi'

child_elem = driver.find_element_by_xpath("//*[@title='hi']")

Then fetch that element's parent using the xpath '..'

parent_elem = child_elem.find_element_by_xpath('..')

Now, to fetch the parent element's attribute id, simply do

parent_elem.get_attribute('id')

Jayesh Doolani
  • 1,233
  • 10
  • 13
  • The answer is right, however the real problem was that I put *find_elements_by_xpath* and not * find_element_by_xpath*, as you said above – Matteo Secco Mar 22 '17 at 15:41
  • You can just do it in one shot with the XPath, `//div[@title='hi']/..`. – JeffC Mar 22 '17 at 17:47