我在 stackoverflow 上找到了这个 selenium 自动化代码。
我正在尝试运行该程序。它给出了一个错误:
Unable to locate element: {"method":"class name","selector":"gssb_e"}
我检查了该页面上的一些 Web 元素,看看是否能找到类名 gssb_e。但我没有找到。我想修改或更新类名,但我不确定该示例正在尝试访问哪个 Web 元素。你能帮忙吗?
WebDriver driver = new FirefoxDriver();
// Go to the Google Suggest home page
driver.get("http://www.google.com/webhp?complete=1&hl=en");
// Enter the query string "Cheese"
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheese");
// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("gssb_e"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
最佳答案
TL;DR:使用更好的定位策略和明确的等待。
当我手动执行相同操作时,我没有看到具有 gssb_e
类名的元素。
相反,在这种故意制造的“困惑”中,我会尝试坚持更可靠的事情。例如,如果我们尝试等待结果出现,我会显式等待具有 id="search"
的元素变得可见:
WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("search")));
换句话说,与您使用的 gssb_e
类名相比,Google 搜索结果页面上有很多更可靠、更符合逻辑且更简单的内容,可以告诉您结果是准备就绪并可见。
关于java - 从示例中找不到 Selenium 类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491163/