Home > Net >  Python Selenium get nth parent and nth child
Python Selenium get nth parent and nth child

Time:01-16

i am looking for a solution to get the second parent (div) of a known element and then get a child element with sub-childrens in selenium with python.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>


<div >
    <div >...</div>
    <div >
        <div >
            <span >b_Kunden</span>
        </div>
    </div>
    <div >...</div>
    <div >...</div>
    <div >
        <div >
            <div >
                <div >
                    <div >
                        <button type="button" >button i want to click</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div >
    <div >...</div>
    <div >
        <div >
            <span >different</span>
        </div>
    </div>
    <div >...</div>
    <div >...</div>
    <div >
        <div >
            <div >
                <div >
                    <div >
                        <button>some button</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div >
    <div >...</div>
    <div >
        <div >
            <span >different</span>
        </div>
    </div>
    <div >...</div>
    <div >...</div>
    <div >
        <div >
            <div >
                <div >
                    <div >
                        <button>some button</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


</body>
</html>

I am getting the element I am looking for with xpath and checking for a specific text ("b_Kunden")(working fine):

temp = browser.find_elements_by_xpath("//*[contains(text(), 'b_Kunden')]")[0]

** I cannot access it trough simple className etc. This is just dummy HTML in environment I need to go up to p1 class from where span text is "b_Kunden" and then down to child element p6 to click the button inside it **

The reason for this is I need to press exactly the button of the section where the span text is b_Kunden. Because the amount of the sections is variable I cannot count and access them trough example: [1] operator for classes. I need to find the term "b_Kunden" and press the relate button in the p1 section to it.

I would be glad if someone could help me out on how to solve this issue.

Best regards, Liam

CodePudding user response:

This might help you (assuming that the 2nd parent you referred to is going backwards in heirarchy (higher up the DOM):

browser.find_elements_by_xpath("//*[contains(text(), 'b_Kunden')][1]//parent::div//parent::div")

UPDATE (code per the comment and html block provided by @Liam)

//*[text()='b_Kunden']//ancestor::div//button

Here is the HTML with DOM highlighted to the button. I hope this is what you are looking for.

HTML DOM highlighted snapshot

  •  Tags:  
  • Related