且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Selenium WebDriver for Java中按索引查找元素

更新时间:2023-11-18 22:17:04

在您的代码中:

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();
}