Skip to content
Advertisement

How to find parent elements by python webdriver?

Is there any methods for python+selenium to find parent elements, brother elements, or child elements just like

driver.find_element_parent? or
driver.find_element_next? or
driver.find_element_previous?

eg:

<tr>
  <td> 
     <select>
        <option value=0, selected='selected'> </option> 
        <option value=1, > </option>
        <option value=2,> </option>
     </select>
   </td>
   <td> 'abcd'
     <input name='A'> </input>
    <td>
<tr>

I’ve tried like below, but fail:

input_el=driver.find_element_by_name('A')
td_p_input=find_element_by_xpath('ancestor::input')

How can I get the parent of input element and then, finally, get the option selected?

Advertisement

Answer

You can find a parent element by using .. xpath:

input_el = driver.find_element_by_name('A')
td_p_input = input_el.find_element_by_xpath('..')

What about making a separate xpath for getting selected option, like this:

selected_option = driver.find_element_by_xpath('//option[@selected="selected"]')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement