我正在为网站编写一个自动化应用程序。因此我需要转向没有 ID 的 HTML 元素。我听说 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
如果该类名称正确且稳定(在我看来它是生成的,这意味着每次加载页面时都会有不同的类名称,这一更改会破坏您的脚本),我建议使用
WebElement we = d.findElements(By.cssSelector(".gLFyf.gsfi")).get(0);
正如另一个答案所示,By.className() 可能会被类名中的空格混淆。
我是一名优秀的程序员,十分优秀!