Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver Find nth element

I am kinda stuck in a problem and am not able to fix it I have to access nth image on my page which comes in table inside HTML. I need to click on image to move to next screen respectively for each row

I have tried various solution provided here but since I am working with findElement(by) syntax I am not able to run my code with those assistances

My code is:

public void editUser(String userName)
{
    System.out.println("in editUser 1");
    int row = getCellRow(table, userName);
    System.out.println("in editUser 2");

    WebElement  edit = driver.findElement(By.xpath("//*[@class='grid']/tbody/tr[2]/td[8]/a[1]/img"));

    System.out.println("in editUser 3");
    edit.click();
    System.out.println("in editUser 4");
    clickButton(closeButton);
}

Error is :

No such element exception. Unable to locate element: {"method":"xpath", selector"://img[@title='User Management'])[2]

Selenium IDE could recognize my element but not selenium web driver ! Please advice

like image 327
user1726783 Avatar asked Oct 11 '12 03:10

user1726783


People also ask

How do I find the nth element in Selenium?

You can use “tag:nth-of-type(n)”. It will select the nth tag element of the list. Syntax: . tree-branch>ul>li:nth-of-type(3) (Selects 3rd li element.)

How do you find the nth element using XPath?

In case we need to identify nth element we can achieve this by the ways listed below. position() method in xpath. Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1.


2 Answers

Use [ ] to reference the nth element for instance

WebElement  edit = driver.findElement(By.xpath("(//*[@class='grid']//img)[n]"));

Where n is the element number

like image 150
so cal cheesehead Avatar answered Oct 30 '22 15:10

so cal cheesehead


Since the html snippet is not a complete view, its unable to advice if the xpath used is right. With what is presented here, could suggest the following to move forward

  1. Try using xpather (firefox plugin) to check if the xpath used returns the right image you are trying to click.
  2. If above condition passes, then there could be timing issues for the image to load before webdriver tries to find it.
like image 21
Gayathri Avatar answered Oct 30 '22 16:10

Gayathri