Finding bootstrap dropdown menu items with xpath using Selenium

  • 1 Replies
  • 3326 Views
Finding bootstrap dropdown menu items with xpath using Selenium
« on: February 15, 2016, 10:42:15 am »
I am trying to find all 'a' tags of list items under 'ul' in my dropdown menu, in order to automate click() and get content text.

The HTML looks as follows :

Code
<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Samples
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li><a href="#">1</a></li>
      <li><a href="#">2</a></li>
      <li><a href="#">3</a></li>
    </ul>
</div>

I have tried using
Code
List<WebElement> items = driver.findElements(By.xpath("//[local-name()='a']"));
but without much success.
Any suggestions ?
« Last Edit: February 15, 2016, 10:45:11 am by Luthar »

*

Haim

  • *
  • 10
Re: Finding bootstrap dropdown menu items with xpath using Selenium
« Reply #1 on: February 15, 2016, 14:13:46 pm »
Assuming you could locate the dropdown div by class (or assign it an id or any other method)
Code
WebElement dropdown = driver.findElement(By.className("dropdown");
from here on, using relative xpath would be much easier.

Code
List<WebElement> items = dropdown.findElements(By.xpath("//ul//a"));
This would find all anchor tags under your 'ul' and group them into a List.

Alternatively, if you want to be more specific you could do:
Code
List<WebElement> items = dropdown.findElements(By.xpath("//ul/li/a"));
This would only find anchor tags under list items ('li').

I'd strongly advise you to read this article :
http://toolsqa.com/selenium-webdriver/choosing-effective-xpath/
He explains using Xpaths in Selenium quite thoroughly.

 

Sitemap 1 2 3 4 5 6 7 8