xProgramery
xProgramery

Reputation: 517

Clicking on <li> list item not using Selenium Java

The following list represents page navigation buttons:

<div class="list">
 <ul class="pageNav">
  <li class="paginate_button ">
   <a href="#" controls="Tables_Table_0" data-idx="0" tabindex="0">1</a></li>
  <li class="paginate_button ">
   <a href="#" controls="Tables_Table_0" data-idx="1" tabindex="0">2</a></li>
  <li class="paginate_button ">
   <a href="#" controls="Tables_Table_0" data-idx="2" tabindex="0">3</a></li>
 </ul>
</div>

To go to the second page for instance, I am using this Selenium Java code:

//after setting up webdriver
List<WebElement> li = driver.findElements(By.className("pageNav"));
System.out.println(li.get(2).getText());
li.get(2).click();

It's printing the text correctly "2", but not clicking or navigating correctly as if I was manually doing it on the actual website. I also tried replacing the link with an actual link like: <a href="https://www.w3schools.com/html/">Visit our page</a>

But still no luck. What am I doing wrong?

Thank you in advanced!

Upvotes: 1

Views: 1561

Answers (3)

Kushal Bhalaik
Kushal Bhalaik

Reputation: 3384

If you're facing any abnormal difficulty which you are not able to handle directly , then you can first try to move to that element using actions class then click it as below:

 WebElement we = driver.findElement(By.cssSelector("div.list > ul.pageNav li:nth-child(2));
 Actions action = new Actions(driver);
 action.moveToElement(we).click().build().perform();

Upvotes: 1

Jainish Kapadia
Jainish Kapadia

Reputation: 2611

Try any of these below code.

In your tried code, I have noticed that you were using class locator to click on links element. But your <ul> tag does not contains the link. Inside <ul> tag, <li> tag is present and each <li> tag contains separate <a> tag.

so, here you should go with xpath or cssSelector locator.

Method 1) By using xpath locator

List<WebElement> links = driver.findElements(By.xpath("//ul[@class='pageNav']/li/a"));
System.out.println(links.size());

links.get(1).click(); //indexing start from 0, if you want to click on second link then pass indexing as 1.

Suggestion:- Instead of using absolute xpath, use relative xpath.

Method 2) By using cssSelector locator

List<WebElement> links = driver.findElements(By.cssSelector("ul.pageNav>li>a"));
System.out.println(links.size());

links.get(1).click(); //indexing start from 0, if you want to click on second link then pass indexing as 1.

Upvotes: 1

Akarsh
Akarsh

Reputation: 967

Try below code

    //getting all the anchor tag elements and storing in a list

    List<WebElement> links = driver.findElements(By.xpath("//ul[@class='pageNav']//li[starts-with(@class,'paginate_button')]/a"));
    System.out.println(links.size());

    //performs click on second links
    links.get(1).click();

Upvotes: 1

Related Questions