Nabz Nabz - 4 months ago 13
Java Question

Accessing specific element of data-ri/data-row with Selenium

I'm using Selenium in Java and I am learning Selenium to run simple tests. The test I am doing is to:


  1. Open Firefox

  2. Open Google

  3. Go on Images and search Google

  4. Click the second image



I noticed on google images they have under the div they have
data-ri
and
data-row
, so for example the first row is
data-row=0
, and the second element is
data-ri=1
, and the class is
rg_di
. How would I write a code in Java using Selenium to get the second element from the image search. I was thinking of using Xpath but I got confused.

EDIT (Forgot to post the code I had before):

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.ca");

System.out.println("Page title: " + driver.getTitle());
String title = driver.getTitle();

driver.manage().window().maximize();
Assert.assertTrue(title.contains("Google"));
Assert.assertFalse(title.contains("Yahoo"));


driver.findElement(By.linkText("Images")).click();
driver.findElement(By.id("lst-ib")).sendKeys("google");
driver.findElement(By.id("sblsbb")).click();

driver.findElement(By.className("rg_l")).click();
}

Answer

Here data-row represent the row index and data-ri represent index of image where both are start with 0 index, you can simply find the exact image using By.cssSelector() by passing data-ri attribute index of the image, as in your case if you want second image, you should simple use as below :-

String imageIndex = "1";
WebElement image = driver.findElement(By.cssSelector("div[data-ri = '" + imageIndex + "'] img"));

Note:- If you want other image just change imageIndex with which you want.