Reputation: 1902
Given an XML structure like so:
<ul>
<li role="treeitem" aria-level="1" aria-expanded="true">
<span role="presentation"></span>
<span>
<span>Seasons</span>
</span>
</li>
<ul>
<li role="treeitem" aria-level="2" aria-expanded="false">
<span role="presentation"></span>
<span>
<span>Winter months</span>
</span>
</li>
<ul></ul>
<li role="treeitem" aria-level="2" aria-expanded="true">
<span role="presentation"></span>
<span>
<span>Spring months</span>
</span>
</li>
<ul >
<li role="treeitem" aria-level="3" >
<span>
<span>March</span>
</span>
</li>
<ul></ul>
<li role="treeitem" aria-level="3">
<span>
<span>April</span>
</span>
</li>
<ul></ul>
<li role="treeitem" aria-level="3">
<span>
<span>May</span>
</span>
</li>
<ul></ul>
</ul>
<li role="treeitem" aria-level="2" aria-expanded="false">
<span role="presentation"></span>
<span>
<span>Summer months</span>
</span>
</li>
<ul></ul>
<li role="treeitem" aria-level="2" aria-expanded="false">
<span role="presentation"></span>
<span>
<span>Autumn months</span>
</span>
</li>
<ul></ul>
</ul>
</ul>
where <span role="presentation"></span>
are buttons, when clicked, open a tree branch. aria-expanded = 'true'
means opened branch.
li
element containing the text 'Winter months'
inside the child tags (save this in String xpathToLi
)?the aria-expanded
attribute from the found path xpathToLi
?aria-expanded = 'false'
inside the xpathToLi
path, find into xpathToLi
the element with role = 'presentation'
and click on it.Upvotes: 0
Views: 651
Reputation: 585
Assuming you are using java.
WebElement xpathToLi = driver.findElement(By.xpath("//span[text()='Winter months']/ancestor::li"));
String ariaExpanded = xpathToLi.getAttribute("aria-expanded");
if(ariaExpanded.equalsIgnoreCase("false")) {
xpathToLi.findElement(By.xpath("./span[@role='presentation']")).click();
}
Upvotes: 1
Reputation: 193088
To extract the value of the attribute aria-expanded
for the season of i.e. Winter months you can use the following solution:
Java based xpath solution:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul//span[text()='Seasons']//following::ul[1]//span[text()='Winter months']//preceding::li[1]"))).getAttribute("aria-expanded"));
Python based xpath solution:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//ul//span[text()='Seasons']//following::ul[1]//span[text()='Winter months']//preceding::li[1]"))).get_attribute("aria-expanded"))
Upvotes: 0