Im trying to automate the Google Images page:
All the images have the same class but no id and the results are constantly changing. So I would like to be able to click on the images based on their index.
I know how to do it in C#...but I cant figure out how to specify in the index in Java. When I try to select an index beyond 0, I get and IndexOutOfBounds error, but i cant figure out why
WebElement image = chromeDriver.findElement(By.className("rg_di"));
WebElement imageLink = image.findElements(By.tagName("a")).get(1);
imageLink.click();
Here is the entire code im using...any help would be appreciated:
System.setProperty("webdriver.chrome.driver", "/Users/user/chromedriver");
WebDriver chromeDriver = new ChromeDriver();
chromeDriver.get("http://www.google.com");
WebElement searchBox = chromeDriver.findElement(By.id("gbqfq"));
searchBox.sendKeys("pluralsight");
searchBox.sendKeys(Keys.RETURN);
chromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement imagesLink = chromeDriver.findElement(By.linkText("Images"));
imagesLink.click();
WebElement image = chromeDriver.findElement(By.className("rg_di"));
WebElement imageLink = image.findElements(By.tagName("a")).get(1);
imageLink.click();
Any help would be greatly appreciated
This code worked very well when we have similar object properties for same web buttons, then using
and then getting
Thank you so much for posting this answer.
I'd do:
In your code:
will return the first element found on the page with a class of "rg_di".
That element has only one
<a href=... /a>
tag in it.You are getting an IndexOutOfBounds exception because you are asking for the second one (zero based indexing). If you change your final WebElement to:
The code should work for you with that small change.
This is my quick version (note the lack of storing elements I only need to do one thing with as WebElements):
Another solution may be like this: If the class name and the index of the web element are known, then following code works: