Как найти родительский элемент selenium

I have a certain element that I can select with Selenium 1.

Unfortunately I need to click the parent element to get the desired behaviour. The element I can easily locate has attribute unselectable, making it dead for clicking. How do I navigate upwards with XPath?

Peter Mortensen's user avatar

asked Dec 20, 2011 at 15:18

f l's user avatar

There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.

Java:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
                                   "return arguments[0].parentNode;", myElement);

XPath:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));

Obtaining the driver from the WebElement

Note: As you can see, for the JavaScript version you’ll need the driver. If you don’t have direct access to it, you can retrieve it from the WebElement using:

WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();

Steven's user avatar

Steven

5,1142 gold badges26 silver badges38 bronze badges

answered Aug 1, 2013 at 18:21

acdcjunior's user avatar

acdcjunioracdcjunior

131k36 gold badges331 silver badges304 bronze badges

3

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* – returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] – returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* – returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">

  1. //span/ancestor-or-self::* – returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">

  1. //span/ancestor::div[2] – returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

answered Aug 19, 2017 at 9:16

Andersson's user avatar

AnderssonAndersson

51.4k16 gold badges74 silver badges127 bronze badges

1

Let’s consider your DOM as

<a>
    <!-- some other icons and texts -->
    <span>Close</span>
</a>

Now that you need to select parent tag ‘a’ based on <span> text, then use

driver.findElement(By.xpath("//a[.//span[text()='Close']]"));

Explanation: Select the node based on its child node’s value

Archmede's user avatar

Archmede

1,5282 gold badges19 silver badges37 bronze badges

answered Mar 23, 2017 at 17:04

Bhuvanesh Mani's user avatar

3

Take a look at the possible XPath axes, you are probably looking for parent. Depending on how you are finding the first element, you could just adjust the xpath for that.

Alternatively you can try the double-dot syntax, .. which selects the parent of the current node.

drkthng's user avatar

drkthng

6,5817 gold badges32 silver badges53 bronze badges

answered Dec 20, 2011 at 16:01

prestomanifesto's user avatar

prestomanifestoprestomanifesto

12.5k5 gold badges33 silver badges50 bronze badges

This might be useful for someone else:
Using this sample html

<div class="ParentDiv">
    <label for="label">labelName</label>
    <input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
    <label for="animal">pig</label>
    <input type="button" value="elementToSelect">
</div>

If for example, I want to select an element in the same section (e.g div) as a label, you can use this

//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect'] 

This just means, look for a label (it could anything like a, h2) called labelName. Navigate to the parent of that label (i.e. div class="ParentDiv"). Search within the descendants of that parent to find any child element with the value of elementToSelect. With this, it will not select the second elementToSelect with DontSelect div as parent.

The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need.
Other Syntax like following-sibling::h2 can also be used in some cases. This means the sibling following element h2. This will work for elements at the same level, having the same parent.

answered Jan 25, 2017 at 14:16

papigee's user avatar

papigeepapigee

6,1933 gold badges28 silver badges31 bronze badges

We can select the parent tag with the help of Selenium as follows:

driver.findElement(By.xpath("//table[@id='abc']//div/nobr[.='abc']/../.."));

this will help you to find the grandparent of the known Element. Just Remove one (/..) to find the immediate Parent Element.

Like:

driver.findElement(By.xpath("//table[@id='abc']//div/nobr[.='abc']/..));

There are some other ways to implement this, but it worked fine for me.

Eric Aya's user avatar

Eric Aya

69.3k35 gold badges180 silver badges251 bronze badges

answered Sep 11, 2017 at 9:29

Utsav Jain's user avatar

0

You can do this by using /parent::node() in the xpath. Simply append /parent::node() to the child elements xpath.

For example:
Let xpath of child element is childElementXpath.

Then xpath of its immediate ancestor would be childElementXpath/parent::node().

Xpath of its next ancestor would be childElementXpath/parent::node()/parent::node()

and so on..

Also, you can navigate to an ancestor of an element using
'childElementXpath/ancestor::*[@attr="attr_value"]'. This would be useful when you have a known child element which is unique but has a parent element which cannot be uniquely identified.

answered Dec 8, 2016 at 4:38

Johnes Jose's user avatar

Have once way you don’t need to execute script and you still get the parent element:

  // identify element
  WebElement ele =driver.findElement(By.xpath("//*[@id="ext-gen6"]/div[5]/"));
  //identify parent element with ./.. expression in xpath
  WebElement parent = ele.findElement(By.xpath("./.."));

The key word here is xpath “./..”

answered Jun 21, 2022 at 2:16

Sang9xpro's user avatar

Sang9xproSang9xpro

4255 silver badges8 bronze badges

I have multiple tables on a website, I need to find the table with element that has text ‘blabla’ and then in that same table I will press a button, I tried this:

a = browser.find_element_by_xpath(f'//*[contains(text(),"blabla")]')
b = a.find_element_by_xpath('..')
browser.find_element_by_xpath(f'{b}/btn').click()

b --> <selenium.webdriver.remote.webelement.WebElement (session="0c5008a89c2da6d4b2e83f4237afc6ba", element="ef8fddcc-88fb-4947-b2c2-2e5ac400b5a1")>

but it gave me that this is an invalid xpath, as b is not the xpath but rather something else I don’t understand, so does anyone have any idea how to do this correctly ? or if it is possible

EDIT:
this is an example for a table

<tr style="height:30px;">
            <td valign="top" style="width:50px;">
                            <b>Code:</b><br>
                            <a href="editcourse_lookup.aspx?coursecode=SB32173" target="_blank">
                                SB32173
                            </a>
                            <br>
                            <br>
                            Azan - Tajweed ul Quran Level 1
                            <br>
                            
                            
                            <a href="javascript:void(0);" onclick="window.open('learningplan_welcome.aspx?coursecode=SB32173&amp;teacherid=365&amp;studid=13150&amp;regNo=22478','windowname1','width=900, height=600');return false;" target="_blank">View Report</a>
                            <br>
                            <a href="javascript:void(0);" onclick="window.open('Convert-report.aspx?coursecode=SB32173&amp;teacherid=365&amp;studid=13150&amp;regNo=22478','windowname1','width=550, height=180');return false;" target="_blank">Convert Report</a>
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblpuseddetails_0"></span>
                              <br>
                            
                                <br>
                             <a href="editsubs.aspx?mode=Modify&amp;courseCode=SB32173&amp;sid=13150&amp;uid=musafdar@uncg.edu&amp;g=All&amp;type=s&amp;parentpage=y" target="_blank">Edit</a>
                            <br>
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblSubjectdetails_0" style="font-size:10px;"><b>Member Name:</b>Osman Khan<br><b>Subject:</b>Tajweed ul Quran Level 1<br><b>Curriculum:</b><br><b>Material:</b>Tajweed ul Quran Level 1</span>

                        </td><td align="center" style="width:130px;">
                            
                            
                            
                            
                            Wed, 04 Aug 2021
                            -
                            Wed, 29 Sep 2021
                            <br>
                            Wed, 1:00 AM - 2:00 AM<br>Fri, 1:00 AM - 2:00 AM<br>Sun, 3:00 PM - 4:00 PM
                            <br>
                            <a href="editCourse1To1.aspx?mode=Modify&amp;courseCode=SB32173" id="ContentPlaceHolder3_gv_1To1CourseDetails_a_EditCourse_0" style="color: Blue;">Modify</a><br>
                            <a id="ContentPlaceHolder3_gv_1To1CourseDetails_a_NewSubscr_0" style="color: Blue;cursor:pointer;" title="Book New Subscription" onclick="window.open('addcourse_1To1.aspx?reg=old&amp;mode=new&amp;catid=1&amp;coursecode=SB32173&amp;studentid=13148&amp;username=Irfan safdar&amp;timezone=13&amp;country=869&amp;sid=13150&amp;g=All&amp;type=s','windowname1','location=1,status=1,scrollbars=1,width=900, height=650')">
                           Book New Subscription
                            </a>
                            <br><br>
                              <a onclick="return confirm('Are you Sure to Reschedule ?');" id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkReschedule_0" title="Click to Reschedule" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkReschedule','')">Reschedule</a>
                            
                             
                              
                        </td><td align="center">
                         Fri, 1:00 AM - 2:00 AM<br>Sun, 3:00 PM - 4:00 PM<br>Wed, 1:00 AM - 2:00 AM<br>20<br>0.00<br><a href="popup/updatesubscriptionpackage.aspx?coursecode=SB32173&amp;sid=13150&amp;subsno=155534" target="_blank">Amend Default Subscription</a><br><br><a href="popup/Reschedule_Remaining_classes.aspx?coursecode=SB32173&amp;mode=CD" target="_blank">Amend Current Subscription</a>
                        
                       </td><td align="center">
                            
                            Mohamed Sawy
                            <br>
                            <a href="Send_Email.aspx?emailcode=Teacher_Confirm&amp;coursecode=SB32173&amp;back_sid=13150&amp;back_g=All&amp;back_type=s">
                                Confirm()</a>
                            <br>
                            <a href="Send_Email.aspx?emailcode=Teacher_Cancel&amp;coursecode=SB32173&amp;back_sid=13150&amp;back_g=All&amp;back_type=s">
                                Cancel()</a>
                                
                                <br><a target="_blank" href="PopUp/createmessage.aspx?mode=Teacher&amp;tid=365"><img src="images/email.jpg" width="25" height="19"></a><a target="_blank" href="PopUp/SMSText.aspx?mode=Teacher&amp;tid=365"><img src="images/text.jpeg" width="22" height="20"></a><a target="_blank" href="PopUp/call.aspx?mode=Teacher&amp;tid=365" '=""><img src="images/iphone-call-icon.jpg" width="22" height="20"></a><a target="_blank" title="Student Notes" href="PopUp/teachernotes.aspx?tid=365" '=""><img src="images/notes.jpeg" width="22" height="20"></a>
                                <br>
                                <a href="popup/Update_Teacher.aspx?coursecode=SB32173" target="_blank">Change Teacher</a>
                                 <br><br><a href="https://secure.examhelper.org/eaalim/teacher/calendar/default.aspx?tid=365" target="_blank">View Teacher Calendar</a>
                        </td><td align="center" style="width:50px;">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblinvoiceno_0">22478</span><br>
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblinvoicedate_0">Wed, 04 Aug 2021</span>
                        </td><td align="center" style="width:50px;">
                            <a href="SendInvoice_1To1.aspx?coursecode=SB32173&amp;back_sid=13150&amp;back_g=All&amp;back_type=s">
                                Invoice(0)</a>
                        </td><td align="center">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblNoOfLessons_0">20</span>
                        </td><td align="center" style="width:50px;">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblAttended_0">0</span>
                        </td><td align="center" style="width:50px;">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblAbsent_0">1</span>
                        </td><td align="center">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblMarkup_0">0 out of 5</span><br>
                            <a href="javascript:void(0);" onclick="window.open('edit-markup.aspx?coursecode=SB32173','windowname1','width=400, height=180');return false;" target="_blank">Modify</a>
                        </td><td align="center" style="width:50px;">
                            
                           
                            19
                            <hr>
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblTotalLessonHtml_0" style="font-size:9px;"><b>Total Lessons:</b>20<br><b>Total Hrs:</b>20<br><b>Total Lessons Left:</b>19<br><b>Total Hrs Left:</b>5<br><b>Total Extra Lessons Left:</b>0<br><b>Total Extra Hrs Left:</b>0mins<br><b>Total Free Lessons Left:</b>0<br><b>Total Free Hrs Left:</b>0mins</span>
                              <hr>
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblmissinglessons_0">20/20=0 missing</span>
                        </td><td align="right" style="width:50px;">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblcoursefee_0">0&nbsp;£</span>
                        </td><td align="center">
                            <a href="viewlessons.aspx?courseid=SB32173&amp;regno=22478&amp;cname=Azan - Tajweed ul Quran Level 1" target="_blank">View</a><br><br><br>
                                 <a href="popup/addCourseLesson.aspx?id=SB32173" target="_blank">
                                Add Lessons
                            </a>
                        </td><td align="center">
                            <span id="ContentPlaceHolder3_gv_1To1CourseDetails_lblBooked_0">Enroled </span>
                        </td><td align="center">
                            <a onclick="return confirm('Are you Sure to change Live Chat Status ?');" id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkLiveChatStatus_0" title="Click to Active/InActive" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkLiveChatStatus','')">Active</a>
                        </td><td align="center">
                            
                            Active

                            <select name="ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlStatus" onchange="return ShowConfirm(this);setTimeout('__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlStatus','')', 0)" id="ContentPlaceHolder3_gv_1To1CourseDetails_ddlStatus_0" style="border-color:#999999;border-width:1px;border-style:Solid;font-family:Verdana;font-size:11px;">
                <option selected="selected" value="">Change Status</option>
                <option value="Active">Active</option>
                <option value="Archive">Archive</option>
                <option value="Inactive">Inactive</option>
                <option value="Cancelled">Cancelled</option>

            </select>
                             <br> <br>
                                         <select name="ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlAction" onchange="javascript:setTimeout('__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlAction','')', 0)" id="ContentPlaceHolder3_gv_1To1CourseDetails_ddlAction_0" style="border-color:#999999;border-width:1px;border-style:Solid;font-family:Verdana;font-size:11px;width:170px;">
                <option selected="selected" value="">Pause Course - select</option>
                <option value="Pause Course">Pause Course with pending lessons</option>

            </select>

                        </td><td align="center">
                            
                        </td><td align="center">
                       
                        <select name="ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$drpwhiz" id="ContentPlaceHolder3_gv_1To1CourseDetails_drpwhiz_0" style="border-color:#999999;border-width:1px;border-style:Solid;font-family:Verdana;font-size:11px;">
                <option selected="selected" value="999,zoomfree">Zoom Free</option>
                <option value="1,braincert">Braincert</option>
                <option value="1,wiziq">WizIQ 25</option>
                <option value="2,wiziq">WizIQ 100</option>
                <option value="3,wiziq">WizIQ 500</option>

            </select>
                                  <br>
                                   <a id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkswhiz_0" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkswhiz','')">Go</a>
                             <br>
                            <a onclick="alert('You have already generated the lesson url for this course.');" id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkGenUrl1_0" title="Already Generated" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkGenUrl1','')">Generated</a>
                            
                            <hr>
                             <a onclick="return confirmGenUrl();" id="ContentPlaceHolder3_gv_1To1CourseDetails_LinkButton1_0" title="Click to Generate url" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$LinkButton1','')">Re-Generate Existing URL</a>
                        </td><td align="center">
                              <a onclick="return confirm('Are sure want to request for ecertficate?');" id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkRequestCertificate_0" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkRequestCertificate','')">Request eCertificate(0)</a>

                            <br>
                            <a href="Certificate-logs.aspx?coursecode=SB32173" target="_blank">Send Certificate</a>
                             <br>
                            <a onclick="return confirm('Are you Sure to Delete ?');" id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkactive11_0" title="Click to Delete" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkactive11','')">Delete</a>
                            <br>
                            <a id="ContentPlaceHolder3_gv_1To1CourseDetails_lnkstatusActive_0" href="javascript:__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$lnkstatusActive','')">Active SMS</a>
                              <br>
                             <select name="ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlclasstype" onchange="javascript:setTimeout('__doPostBack('ctl00$ContentPlaceHolder3$gv_1To1CourseDetails$ctl02$ddlclasstype','')', 0)" id="ContentPlaceHolder3_gv_1To1CourseDetails_ddlclasstype_0" style="border-color:#999999;border-width:1px;border-style:Solid;font-family:Verdana;font-size:11px;">
                <option selected="selected" value="Auto">Auto</option>
                <option value="Manual">Manual</option>

            </select>
                        </td>
        </tr>

This is a quick article to show how you can easily get the parent element of an HTML element using Selenium Webdriver with Python. There is more than one way.

Let’s suppose that we want to get an HTML button that has no id or unique CSS class from within an HTML page:

<html>
<body>
...
  <button>
   <span id="account-login-submit-message">Login</span>
  </button>
...
</body>
</html>

1. Getting Parent element using XPATH ..

First, we can retrieve the HTML Element for the <span> tag using the id:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")

Then you can retrieve the parent element using XPATH by simply calling:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
submitLoginButton = submitLoginSpan.find_element_by_xpath("..")
submitLoginButton.click()

2. Getting Parent Element directly using XPATH ancestor

We can also etrieve the parent element of an element using XPATH :ancestor::<TAG_NAME>. Where the TAG_NAME Is the name of the tag of the HTML Element that we are trying to retrieve.

submitLoginButton = wd.find_element_by_xpath('//span[@id="account-login-submit-message"]/ancestor::button')
submitLoginButton.click()

3. Getting Parent Element using CSS Selector

Currently, there is no way of selecting a parent element using a CSS Selector, hence I included it here to shorten your search.

4. Getting Parent Element using element.parent

You might be tempted to write the following code:

submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
submitLoginButton = submitLoginSpan.parent
submitLoginButton.click()

But you will get an error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_27716/2471411830.py in <module>
      1 submitLoginSpan = wd.find_element_by_id("account-login-submit-message")
      2 submitLoginButton = submitLoginSpan.parent
----> 3 submitLoginButton.click()

AttributeError: 'WebDriver' object has no attribute 'click'

This is because the .parent attribute returns a reference to Selenium WebDriver instance that contains this HTML Element. It is not returning the actual parent HTML Element

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies

    This article revolves around how to use parent method in Selenium. parent method is used to get internal reference to the WebDriver instance this element was found from.

    Syntax –

    element.parent

    Example –

    <input type="text" name="passwd" id="passwd-id" />

    To find an element one needs to use one of the locating strategies, For example,

    element = driver.find_element_by_id("passwd-id")
    element = driver.find_element_by_name("passwd")
    element = driver.find_element_by_xpath("//input[@id='passwd-id']")

    Also, to find multiple elements, we can use –

    elements = driver.find_elements_by_name("passwd")

    Now one can get parent of this element with –

    element.parent

    How to use parent element method in Selenium Python ?

    Let’s try to get element and its parent method on geeksforgeeksusing parent method.
    Program –

    from selenium import webdriver

    driver = webdriver.Firefox()

    element = driver.find_element_by_id("gsc-i-id2")

    print(element.parent)

    Output-

    clear element method - Selenium Python

    Terminal Output –
    parent-element-method-Selenium-Python

    Last Updated :
    30 Apr, 2020

    Like Article

    Save Article

    We can find parent elements with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name,xpath or css. Then we have to identify the parent element with the find_element_by_xpath() method.

    We can identify the parent from the child, by localizing it with the child and then passing (..) as a parameter to the find_element_by_xpath().

    Syntax−

    child.find_element_by_xpath(“..”)

    Let us identify class attribute of parent ul from the child element li in below html code−

    The child element with class heading should be able to get the parent element having toc chapters class attribute.

    Example

    from selenium import webdriver
    driver = webdriver.Chrome(executable_path="
    C:chromedriver.exe")
    driver.implicitly_wait(0.5)
    driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
    #identify child element
    l= driver.find_element_by_xpath("//li[@class='heading']")
    #identify parent from child element with (..) in xpath
    t= l.find_element_by_xpath("..")
    # get_attribute() method to obtain class of parent
    print("Parent class attribute: " + t.get_attribute("class"))
    driver.close()

    Output

    Добавить комментарий