1、行为日志记录
练习代码:
package com.ceshiren;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
public class KeyInfoTest {
private static WebDriver driver;
public static Logger logger;
@BeforeAll
public static void setUp(){
logger = LoggerFactory.getLogger(KeyInfoTest.class);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3000));
driver.manage().window().maximize();
}
@AfterAll
public static void tearDown(){
driver.quit();
}
@Test
void logInfoTest(){
logger.debug("百度搜索测试开始");
driver.get("https://www.baidu.com/");
driver.findElement(By.id("kw")).sendKeys("hogwarts");
driver.findElement(By.id("su")).click();
String repinfo = driver.findElement(By.id("1")).getText();
logger.info("查找结果是:"+repinfo);
}
}
2、步骤截图记录
代码:
@Test
void screentest() throws IOException {
driver.get("https://www.baidu.com/");
//第一种方法,对整个页面进行截图
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//保存文件
FileUtils.copyFile(srcFile,new File("./img2.png"));
//第二种方法,对单个元素进行截图
driver.findElement(By.id("kw")).sendKeys("hogwarts");
driver.findElement(By.id("su")).click();
WebElement repinfo = driver.findElement(By.id("1"));
File crrentFile = repinfo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(crrentFile,new File("./img3.png"));
}
3、pagesource记录
代码:
@Test
void pageSourceTest() throws InterruptedException, IOException {
driver.get("https://www.baidu.com");
//直接获取pagesource
String pageInfo = driver.getPageSource();
logger.info(pageInfo);
//把信息放在一个文件中
FileWriter fileWriter = new FileWriter("./pageSource.html");
fileWriter.write(pageInfo);
//页面变化较多时,页面元素可能一直在变
// 解决方法:循环获取不同时间段的pagesource,对比变化
int i = 0;
while (i<=3){
Thread.sleep(2000);
String pageInfo2 = driver.getPageSource();
// logger.info(“第”+i+“秒后的pagesource信息为:”+pageInfo2);
FileWriter fileWriter2 = new FileWriter("./pageSource"+i+".html");
fileWriter2.write(pageInfo2);
i++;
}