版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37581708/article/details/80883981
Selenium+java 获取页面的console.log()内容,并且获取默认用户的配置信息,chrome支持获取,Firefox不支持,会报错。
下面 我们用chrome为测试浏览器启动,并获取console.log的内容。
如果不懂chromedriver.exe如何配置,或者user-data-dir在哪里,在本分类第一章中查看。
//配置谷歌启动的必要设置
System.setProperty("webdriver.chrome.bin", "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe");
System.setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");
//设置Webdriver启动chrome为默认用户的配置信息(包括书签、扩展程序等)
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/acer/AppData/Local/Google/Chrome/User Data");
//为了获取console的日志输出
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.INFO);//输入为info的日志
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
caps.setCapability(ChromeOptions.CAPABILITY, options);
//传入谷歌启动器中
WebDriver driver = new ChromeDriver(caps);
driver.manage().window().maximize();//窗口最大化
driver.get("https://blog.csdn.net/qq_37581708");//打开测试地址
以上是打开地址前的配置
下面是 打开后获取console的java代码,最好封装成一个方法 ,哪里需要调哪里。
//获取全部的console信息
LogEntries logEntries =driver.manage().logs().get(LogType.BROWSER);
Thread.sleep(1000);
for(LogEntry entry : logEntries) {
//依次打印出console信息
System.out.println("chrome.console===="+" "+entry.getMessage());
}
// 下面是 根据业务需求编写的 获取信息
/*Thread.sleep(1000);
List<LogEntry>list=driver.manage().logs().get(LogType.BROWSER).getAll();
String content=list.get(list.size()-1).getMessage();//根据需求获取最后一次信息
String tempStr=content.substring(content.indexOf("\"") + 1, content.lastIndexOf("\""));
System.out.println(tempStr);//本次需要获取的某列信息*/