对于selunium的首次使用,安装网上的教程进行了简单安装.环境为:Mac,idea,maven.
使用maven进行包的管理非常方便,所以在pom.xml中添加selenium依赖:
org.seleniumhq.selenium
selenium-java
3.4.0
并写了一个Java的测试类.如下:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Itest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://www.baidu.com");
String title = driver.getTitle();
System.out.println(title);
driver.close();
}
}
运行发现报错了.错误如下:Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.
at TestJava.Itest.main(Itest.java:9)
然后就各种百度,分别做了以下几件事:
1.根据Chrome的版本下载相应的驱动: chromedriver,在Mac中,需要将前面所说的驱动文件放置在Chrome所在的位置.Mac上一般为:
/Applications/Google Chrome.app/Contents/MacOS/.不然会报path问题.
2.在代码中添加
System.setProperty("webdriver.chrome.driver", "/Applications/Google Chrome.app/Contents/MacOS/chromedriver");指出驱动的位置.
到这里为止,问题还是没有解决.而且报错都没有变.
3.接下来在pom.xml中添加
com.google.guava
guava
21.0
好啦,问题解决了!
上面的问题,似乎找到了更好的解决之道.这里讲述的是Chrome浏览器,对于firefox也是如此尝试的.
1.使用什么浏览器则需要下载相关的驱动.
Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
Firefox:https://github.com/mozilla/geckodriver/releases
2.然后将下载的文件解压到/usr/local/bin下就可以了.代码中不需要设置System.setProperty()了.
public class testDriver { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("https://baidu.com"); } }