How to find element by index in selenium webdriver for java
I am trying to automate the Google Images page:
All images are of the same class, but no ID, and the results are constantly changing. So I would like to be able to click on images by their index.
I know how to do this in C # ... but I cannot figure out how to point in the index in Java. When I try to select an index outside of 0, I get an IndexOutOfBounds error as well, but I can't figure out why
WebElement image = chromeDriver.findElement(By.className("rg_di"));
WebElement imageLink = image.findElements(By.tagName("a")).get(1);
imageLink.click();
Here is all the 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
source to share
In your code:
WebElement image = chromeDriver.findElement(By.className("rg_di"));
will return the first element found on the page with the class "rg_di".
This element contains only one tag <a href=... /a>
.
You are getting an IndexOutOfBounds exception because you are asking for the second (zero indexing). If you change your latest WebElement to:
WebElement imageLink = image.findElements(By.tagName("a")).get(0);
The code should work for you with this small change.
This is my swift version (note the lack of element storage, which I only need to do with WebElements):
public static void main(String[] args) {
// I don't have Chrome installed >.<
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement searchBox = driver.findElement(By.id("gbqfq"));
searchBox.sendKeys("pluralsight");
searchBox.sendKeys(Keys.RETURN);
driver.findElement(By.linkText("Images")).click();
WebElement image = driver.findElement(By.className("rg_di"));
image.findElements(By.tagName("a")).get(0).click();
// super-shortened version:
// driver.findElement(By.className("rg_di")).findElements(By.tagName("a")).get(0).click();
}
source to share