Issue
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 class="p1">
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<span class="target">b_Kunden</span>
</div>
</div>
<div class="p2">...</div>
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<div class="p4">
<div class="p5">
<div class="p6">
<button type="button" class="b1">button i want to click</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="p1">
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<span class="target">different</span>
</div>
</div>
<div class="p2">...</div>
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<div class="p4">
<div class="p5">
<div class="p6">
<button>some button</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="p1">
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<span class="target">different</span>
</div>
</div>
<div class="p2">...</div>
<div class="p2">...</div>
<div class="p2">
<div class="p3">
<div class="p4">
<div class="p5">
<div class="p6">
<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
Solution
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.
Answered By - Anand Gautam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.