WebDriver的常用API使用方法
- 访问某网页地址
//方法一:
driver.get(baseUrl);
//方法二:
driver.navigate().to(baseUrl);
- 模拟浏览器的前进后退功能
driver.back();
driver.forward();
- 获取当前页面的URL地址
driver.getCurrentUrl();
- 刷新当前页面
driver.navigate().refresh();
完整代码
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.Assert;
public class WebDriverAPIDemo1 {
WebDriver driver;
String url1 = "https://www.baidu.com/";
String url2 = "https://www.sougou.com/";
@BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void VisitPage() throws Exception {
driver.get(url1); //先访问百度首页
driver.get(url2); //在百度首页跳转访问搜狗首页
driver.navigate().back(); //返回上一次访问的百度首页
//断言当前页面的URL地址是否为"https://www.baidu.com/"
Assert.assertEquals(url1, driver.getCurrentUrl());
driver.navigate().forward(); //从百度首页跳转到搜狗首页
//断言当前页面的URL地址是否为"https://www.sougou.com/"
Assert.assertEquals(url2,driver.getCurrentUrl());
//刷新当前页面
driver.navigate().refresh();
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}