如何在Selenium WebDriver for Java中按索引查找元素
我正在尝试使Google图片页面自动化:
Im trying to automate the Google Images page:
所有图像都具有相同的类,但没有id,并且结果在不断变化.因此,我希望能够根据索引单击图像.
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.
我知道如何在C#中执行此操作...但是我无法弄清楚如何在Java中的索引中指定.当我尝试选择一个大于0的索引时,出现和IndexOutOfBounds错误,但我不知道为什么
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();
任何帮助将不胜感激
在您的代码中:
WebElement image = chromeDriver.findElement(By.className("rg_di"));
将返回在页面上找到的带有"rg_di"类的第一个元素.
will return the first element found on the page with a class of "rg_di".
该元素中只有一个< a href = .../a>
标记.
That element has only one <a href=... /a>
tag in it.
您正在获取IndexOutOfBounds异常,因为您正在请求 second 一个(基于零的索引).如果您将最终的WebElement更改为:
You are getting an IndexOutOfBounds exception because you are asking for the second one (zero based indexing). If you change your final WebElement to:
WebElement imageLink = image.findElements(By.tagName("a")).get(0);
只需很小的改动,代码就可以为您工作.
The code should work for you with that small change.
这是我的快速版本(请注意,缺少存储元素,我只需要做一件事情作为WebElements):
This is my quick version (note the lack of storing elements I only need to do one thing with as 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();
}