Selenium Webdriver 使用 Firefox 进行 Google 搜索/Selenium 测试



我试图先打开 google.com 然后键入"硒测试"。

我只想使用 eclipse 将className用于网络驱动程序,但出现以下错误。

Exception in thread "main" 
org.openqa.selenium.NoSuchElementException: Unable to locate element: 
{"method":"class name","selector":"Tg7LZd"}
Command duration or timeout: 37 milliseconds

这是我的代码:

package coreJava;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Training1 {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.findElement(By.className("gLFyf")).sendKeys("selenium testing");     
driver.findElement(By.className("Tg7LZd")).click();
}
}

我该如何解决这个问题?

此错误消息...

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"Tg7LZd"}

。意味着壁虎驱动程序无法根据您使用的定位器策略找到任何元素。

你的主要问题是你使用的classNames是基于JavaScript的,并且是动态生成的,在生成之前我们无法猜测。 作为替代方法,您可以使用以下解决方案:

package coreJava;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Training1 {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement myElement = driver.findElement(By.name("q"));  
myElement.sendKeys("selenium testing");
myElement.submit();
}
}
System.setProperty("webdriver.gecko.driver", "geckodriver");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://google.com");
Thread.sleep(3);
driver.findElement(By.className("gsfi")).sendKeys("selenium testing");
Thread.sleep(3);
driver.findElement(By.className("sbqs_c")).click();
Thread.sleep(3);
driver.close(); 

这是工作代码

. 这些将打开谷歌浏览器,然后在搜索框中写"硒测试",然后使用该类进行搜索。

最新更新