In this post, discussing about how to get all the content which are collapsible under the accordion. i.e; Open accordion and iterate through each element in the accordion and display those names in the console.
Consider an example from the website http://www.hamaracoupons.in/.
- Access the website http://www.hamaracoupons.in/all-categories
- Here in the page all the categories accordion contains sub-categories. And first listed category already expandable.
- I have a scenario like, get all the sub-category names and display or print those on the console. Choose other than first category, because it is already opened in the site.
Inspect the accordion element using firebug,
<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s"/>
To find an element need to determine the xpath of that element. Using Firepath xpath will be
.//*[@id='ui-accordion-f-accordion-header-2']/span
Click on that accordion web element using xpath expression as,
WebElement expanded = driver.findElement(By.xpath(".//*[@id='ui-accordion-f-accordion-header-2']/span"));
expanded.click();
Find the xpath of the any one of the sub-element under the list.
<div class="all-store">
<a title="Bath & Body" href="category/beauty-and-health/bath-and-body">Bath & Body</a>
</li>
</li>
</ul>
</div>
.//*[@id='ui-accordion-f-accordion-panel-2']/div/ul/li[1]/a
Observe that, all <li> tags are defined as sub-elements in the html code.
Listout all the sub elements under that accordion using findelements() method.
List<WebElement> allLinks = driver.findElements(By.xpath(".//*[@id='ui-accordion-f-accordion-panel-2']/div/ul/li/a"));
Iterate all the list of elements using for each() loop or Iterator() method from the Iterator interface.
AccordionTest.java
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AccordionTest {
public static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException, MalformedURIException {
driver = new FirefoxDriver();
driver.get("http://www.hamaracoupons.in/all-categories");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
WebElement expanded = driver.findElement(By.xpath(".//*[@id='ui-accordion-f-accordion header-2']/span"));
expanded.click();
//Listout all accordion elements
List<WebElement> allLinks = driver.findElements(By.xpath(".//*[@id='ui-accordion-f-accordion-panel-2']/div/ul/li/a"));
System.out.println(allLinks.size());
/*Iterator<WebElement> itr = allLinks.iterator();
while(itr.hasNext()){
System.out.println(itr.next().getText());}*/
driver.close();
}