Selenium By.className() -> IndexOutOfBoundsException:索引:0,大小:0

Selenium By.className() -> IndexOutOfBoundsException: Index: 0, Size: 0

我正在为网站编写自动化应用程序。因此,我需要引导 HTML 个没有 ID 的元素。我听说 xPath 和 CSS Selector 不是最快的,所以我想改成 By.className()。不幸的是我这不起作用。您可以在下面找到一个演示(实际工具不是自动化 google :D)。

我正在使用 GeckoDriver 0.21.0 和 Selenium 3.13.0

WebDriver d = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor) d;  
d.get("https://www.google.com");
WebElement we = d.findElements(By.className("gLFyf gsfi")).get(0);
js.executeScript("arguments[0].value='test';", we);

HTML Element

首先,让我解决这个问题 "xPath and CSS Selector are not that fastest"。它们慢 纳秒 ,也许!如果您对更多信息感兴趣,请阅读

接下来是你的实际问题。 HTML 中的 class 属性是 space 分隔的 列表 class 名称。在你的By.className()中你只能使用其中的一个

此外,您使用的是 .findElements()(复数形式),并且期望只有一个 WebElement。编译器可能会告诉您,您应该期待 List<WebElement>。那么在您的 .executeScript() 中,这显然是行不通的,因为这再次只需要一个元素。你必须在这里解决你真正想要什么。

如果 class 名称正确且稳定(在我看来它是生成的,这意味着每次加载页面时都会有不同的 class 名称,这种更改会破坏您的脚本), 我建议使用

WebElement we = d.findElements(By.cssSelector(".gLFyf.gsfi")).get(0);

如另一个答案所示,By.className() 可能被您的 class 名称中的 space 弄糊涂了。