public class Demo1 {

    WebDriver driver;

    @BeforeMethod
public void visit(){
//webdriver对象的声明
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} //页面操作,返回上一个页面,前进,刷新
@Test
public void VisitRecentUrl(){
String url1 = "http://www.baidu.com";
String url2 = "http://www.sina.com";
driver.navigate().to(url1);
driver.navigate().to(url2);
driver.navigate().back();//返回到上一个页面
driver.navigate().forward();//前进到下一页面
driver.navigate().refresh();//刷新当前页面
driver.close();
} //操作浏览器窗口
@Test
public void operateBrower(){
//设置浏览器的横纵坐标
Point point = new Point(150, 150);
//设置浏览器的宽高
Dimension dimension = new Dimension(500, 500);
driver.manage().window().setPosition(point);
driver.manage().window().setSize(dimension);
System.out.println(driver.manage().window().getPosition());
System.out.println(driver.manage().window().getSize());
driver.manage().window().maximize();//窗口最大化
driver.get("http//www.baidu.com");
driver.close();
} //获取页面的title属性
@Test
public void getTitle(){
driver.get("http://www.baidu.com");
String title = driver.getTitle();
System.out.println(title);
Assert.assertEquals("百度一下,你就知道", title);
driver.close();
} //获取页面的URL
@Test
public void getCurrentUrl(){
driver.get("http://www.baidu.com");
String currentUrl = driver.getCurrentUrl();
System.out.println(currentUrl);
driver.close();
} //清除文本框中的内容
//在文本框中输入指定内容
@Test
public void clearText() throws InterruptedException{
driver.get("file:///F:/workspace/selenium_day01/text.html");
WebElement input = driver.findElement(By.id("text"));
Thread.sleep(2000);
input.clear(); //清除文本框中的内容
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
input.sendKeys("selenium自动化测试");//在文本框中输入指定内容
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
driver.close();
} //单击按钮
@Test
public void clickButton(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
WebElement button = driver.findElement(By.id("button"));
button.click();//单击按钮
driver.close();
} //鼠标双击元素
@Test
public void doubleClick(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
WebElement inputBox = driver.findElement(By.id("inputBox"));
//声明Action对象
Actions builder = new Actions(driver);
builder.doubleClick(inputBox).build().perform();
driver.close();
} //操作单选下拉列表
@Test
public void operateDropList(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
WebElement element = driver.findElement(By.name("fruit"));
Select dropList = new Select(element);
//判断下拉列表是否可多选
Assert.assertFalse(dropList.isMultiple());
//断言当前选中的选项文本是否为桃子
Assert.assertEquals("桃子", dropList.getFirstSelectedOption().getText());
//选中下拉列表中的第2个选项
dropList.selectByIndex(1);
Assert.assertEquals("橘子", dropList.getFirstSelectedOption().getText());
//使用下拉列表选项的value属性值来选中操作
dropList.selectByValue("lizhi");
Assert.assertEquals("荔枝", dropList.getFirstSelectedOption().getText());
//通过选项的文字来进行操作
dropList.selectByVisibleText("山楂");
Assert.assertEquals("山楂", dropList.getFirstSelectedOption().getText());
} //检查单选列表的选项文字是否条预期
@Test
public void checkSelectText(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
WebElement element =driver.findElement(By.name("fruit"));
Select dropList = new Select(element);
//将下拉列表中期望出现的选项文字存在list集合中,Arrays.asList 将数组转换为list对象
String[] arr = {"桃子","橘子","荔枝","山楂"};
List<String> expect_option = Arrays.asList(arr);
//声明一个新的list,用于存取从页面上获取的所有选 项文字
List<String> act_option = new ArrayList<>();
for(WebElement option : dropList.getOptions()){
act_option.add(option.getText());
//断言预期对象与实际对象是否完全一致
Assert.assertEquals(expect_option.toArray(), act_option.toArray());
}
} //操作多选的选择列表
@Test
public void opertMultiple(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
//找到页面的下拉列表元素
WebElement element =driver.findElement(By.name("fruit2"));
Select dropList = new Select(element);
//判断下拉列表是否支持多选,支持多选isMultiple返回true
Assert.assertTrue(dropList.isMultiple());
//使用选择索引选择橘子选项
dropList.selectByIndex(1);
//使用选择value属性选择荔枝选项
dropList.selectByValue("lizhi");
//使用选项文字选择山楂
dropList.selectByVisibleText("山楂"); //取消所有选项的选中状态
dropList.deselectAll();
//再次选中3个数据
dropList.selectByIndex(1);
dropList.selectByValue("lizhi");
dropList.selectByVisibleText("山楂");
//取消索引为1的选项
dropList.deselectByIndex(1);
//取消value属性为lizhi的选项
dropList.deselectByValue("lizhi");
//取消选项文字为山楂的选项
dropList.deselectByVisibleText("山楂");
driver.close();
} //操作单选框
@Test
public void operateRadio(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
//查找属性值为chengming的单选按钮对象
WebElement element = driver.findElement(By.xpath("//input[@value='chengming']"));
//如果这个单选项未被选中,则执行click()方法选中这个按钮
if(!element.isSelected()){
element.click();
}
//断言属性值为chengming的单选按钮是否处于选中状态
Assert.assertTrue(element.isSelected()); //查找name属性值为username的所有对象
List<WebElement> elements = driver.findElements(By.name("username"));
//查找value属性为lisi的单选按钮对象,如果处于未选中状态,则执行click方法选中
for(WebElement element2 : elements){
if(element2.getAttribute("value").equals("lisi")){
if(!element2.isSelected()){
element2.click();
//断言单选按钮是否被选中
Assert.assertTrue(element2.isSelected());
//成功选中后,退出
break;
}
}
}
} //操作复选框
@Test
public void operateCheckBox() throws Exception{
driver.get("file:///F:/workspace/selenium_day01/text.html");
//查找属性为汽车的复选框元素
WebElement element = driver.findElement(By.xpath("//input[@value='bus']"));
//如果复选框未选中,则选中
if(!element.isSelected()){
element.click();
}
Assert.assertTrue(element.isSelected());
//如果复选框被选中,则取消选中
/*if(element.isSelected()){
element.click();
}
Assert.assertTrue(element.isSelected());*/
//查找属性为fruit3的元素,并选中
List<WebElement> list = driver.findElements(By.name("fruit3"));
for(WebElement checkbox : list){
checkbox.click();
}
Thread.sleep(1000);
driver.close();
} //将当前浏览器窗口截屏
@Test
public void screen(){
driver.get("http://www.baidu.com");
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(file, new File("e:/testing/test.png"));
} catch (IOException e) {
e.printStackTrace();
}
} //检查页面元素内容是否出现
@Test
public void isElementText(){
//判断p标签内容与selenium自动化测试是否完全匹配
driver.get("file:///F:/workspace/selenium_day01/text.html");
WebElement element = driver.findElement(By.xpath("//p[1]"));
String text = element.getText();
System.out.println("》》》》》 "+text);
Assert.assertEquals("selenium自动化测试1", text);
} //执行javascript脚本
@Test
public void executeJavaScript(){
driver.get("http:www.baidu.com");
//声明一个JavaScript执行对象
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title");
     //System.out.println("expected"+title);
Assert.assertEquals("百度一下,你就知道", title); //String bottonText = (String) js.executeScript("var button = document.getElementById('su').type='hidden';");
String bottonText = (String) js.executeScript("var button = document.getElementById('su');return button.value"); System.out.println("》》》》》》"+bottonText);
Assert.assertEquals("百度一下", bottonText);
driver.close();
}
}
public class Demo2 {

    WebDriver driver;

    @BeforeMethod
public void Visitor(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} //模拟键盘的操作
@Test
public void clickKeys(){
driver.get("http://www.baidu.com");
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL);//按下ctrl键
action.keyDown(Keys.SHIFT);//按下shift键
action.keyDown(Keys.ALT);//按下alt键 action.keyUp(Keys.CONTROL);//释放ctrl键
action.keyUp(Keys.SHIFT);//释放shift键
action.keyUp(Keys.ALT);//释放alt键 //模拟键盘在输入框中输入TEST
action.keyDown(Keys.SHIFT).sendKeys("test").perform();
} //模拟鼠标右击事件
@Test
public void rightClickMouse(){
driver.get("http://www.baidu.com");
Actions action = new Actions(driver);
//模拟鼠标右击事件
action.contextClick(driver.findElement(By.id("su"))).perform();
driver.close();
} //在指定元素上方进行鼠标悬浮,及点击悬浮后出现的菜单
@Test
public void roverOnElement() throws Exception{
driver.get("http://www.baidu.com");
Actions action = new Actions(driver);
//在指定元素上进行鼠标悬浮
action.moveToElement(driver.findElement(By.name("tj_briicon"))).perform();;
Thread.sleep(1000);
//点击悬浮后出现的菜单
driver.findElement(By.linkText("糯米")).click();;
driver.close();
} //查看页面元素的属性
@Test
public void getWelementAttribute(){
driver.get("http://www.baidu.com");
String str = "今天天气不错";
WebElement input = driver.findElement(By.id("kw"));
input.sendKeys(str);
String inputText = input.getAttribute("value");
System.out.println("....."+inputText);
Assert.assertEquals(inputText,"今天天气不错");
driver.close();
} //获取页面元素的css属性
@Test
public void getWelementCss(){
driver.get("http://www.baidu.com");
WebElement input = driver.findElement(By.id("kw"));
String cssValue = input.getCssValue("width");
System.out.println("..... "+cssValue);
driver.close();
} //常用的显式等待
@Test
public void testWait(){
//声明一个WebDriverWait对象,设置最长等待时间为10秒
WebDriverWait wait = new WebDriverWait(driver, 10);
//判断页面title是否包含“测试页面”4个字
String str = "测试页面";
wait.until(ExpectedConditions.titleContains("测试页面"));
System.out.println("页面标题出现了‘测试页面’4个字");
} /**
* 判断页面元素是否存在
* @param by
* @return
*/
//提供一个页面元素是否存在的方法
public boolean isEelement(By by){
WebElement element = driver.findElement(by);
if(element != null){
return true;
}
return false;
} @Test
public void testIsEelement(){
driver.get("http://www.baidu.com");
//System.out.println(driver.getTitle());
if(isEelement(By.id("kw"))){
WebElement webElement = driver.findElement(By.id("kw"));
if(webElement.isEnabled()){
webElement.sendKeys("百度的首页搜索框被成功找到");
}
}else { //将测试用例设置为失败,并打印失败原因
Assert.fail("页面的输入框元素未找到");
}
driver.close();
} //使用title属性识别和操作新弹出的浏览器窗口
@Test
public void operteWindow(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
//将当前浏览器窗口句柄存在一个变量中
String parentWindowHandle = driver.getWindowHandle();
//点击页面上的链接地址
driver.findElement(By.xpath("//a")).click();
//获取当前所有打开的窗口的句柄,并存在set中
Set<String> windowHandles = driver.getWindowHandles();
if(windowHandles != null){
for(String windowHandle : windowHandles){
if(driver.switchTo().window(windowHandle).getTitle().equals("百度一下,你就知道")){
driver.findElement(By.id("kw")).sendKeys("百度的首页浏览器窗口被找到");
}else {
Assert.fail("百度的首页浏览器窗口未被找到");
}
//返回到最开始打开的浏览器窗口
driver.switchTo().window(parentWindowHandle);
Assert.assertEquals(driver.getTitle(),"测试页面");
}
}
} //使用页面的文字内容识别和处理新弹出的浏览器窗口
@Test
public void operteWindowByPageSource(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
//将当前浏览器窗口句柄存在一个变量中
String parentWindowHandle = driver.getWindowHandle();
//点击页面上的链接地址
driver.findElement(By.xpath("//a")).click();
//获取当前所有打开的窗口的句柄,并存在set中
Set<String> windowHandles = driver.getWindowHandles();
for(String windowHandle : windowHandles){
try {
if(driver.switchTo().window(windowHandle).getPageSource().contains("百度一下")){
driver.findElement(By.id("kw")).sendKeys("百度首页的浏览器窗口被找到");
}
} catch (NoSuchWindowException e) {
e.printStackTrace();
}
}
//返回到最开始打开的浏览器窗口
driver.switchTo().window(parentWindowHandle);
Assert.assertEquals(driver.getTitle(),"测试页面");
} //操作javascript的Alter窗口
@Test
public void operteAlert(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
//查找到按钮元素
WebElement button = driver.findElement(By.name("btn"));
button.click(); try {
//获取alert对象
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是一个alert弹窗", alert.getText());
//关闭弹窗
alert.accept();
} catch (NoAlertPresentException e) {
Assert.fail("页面alert弹窗未找到");
e.printStackTrace();
}
} //操作javascript的confirm窗口
@Test
public void operteConfirm(){
driver.get("file:///F:/workspace/selenium_day01/text.html");
driver.findElement(By.name("confirmbtn")).click(); try {
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是一个confirm弹窗", alert.getText());
alert.accept(); // 点击确定,关闭弹出窗
//alert.dismiss(); // 点击取消,关闭弹出窗
} catch (NoAlertPresentException e) {
Assert.fail("页面confirm弹窗未找到");
e.printStackTrace();
}
} // 操作javascript的prompt窗口
@Test
public void opertePrompt() throws Throwable {
driver.get("file:///F:/workspace/selenium_day01/text.html");
driver.findElement(By.name("promptbtn")).click(); try {
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是一个prompt弹窗", alert.getText());
alert.sendKeys("好好学习,天天向上");
Thread.sleep(3000);
alert.accept();
} catch (NoAlertPresentException e) {
Assert.fail("页面prompt弹窗未找到");
e.printStackTrace();
}
} /**
* 操作iframe中的页面元素
*/
@Test
public void testFrame(){
driver.get("file:///F:/workspace/selenium_day01/frameset.html");
//必须先进入左侧frame_left.html页面
driver.switchTo().frame("leftframe");
//找到页面上的p标签
WebElement leftFrameText = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是左侧 frame 页面上的文字", leftFrameText.getText()); //从左侧返回到frame_left页面 如果不调用 defaultContent()方法,无法从frame_left进入其他页面
driver.switchTo().defaultContent();
//进入frame_middle页面
driver.switchTo().frame("middleframe");
WebElement middleFrameText = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是中间 frame 页面上的文字", middleFrameText.getText()); driver.switchTo().defaultContent();
driver.switchTo().frame("rightframe");
WebElement rightFrameText = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是右侧 frame 页面上的文字", rightFrameText.getText()); driver.switchTo().defaultContent();
driver.switchTo().frame(1);
WebElement text = driver.findElement(By.tagName("p"));
//System.out.println(">>>>>>"+ text.getText());
Assert.assertEquals("这是中间 frame 页面上的文字", text.getText());
driver.close();
} //使用frame中的html源码内容来操作frame
@Test
public void testHandleFarme(){
driver.get("file:///F:/workspace/selenium_day01/frameset.html");
//找到所有frame标签的内容
List<WebElement> frames = driver.findElements(By.tagName("frame"));
for(WebElement frame : frames){
driver.switchTo().frame(frame);
//判断frame页面源码中是否包含“中间 frame”
if(driver.getPageSource().contains("中间 frame")){
//找到页面P标签页面对象
WebElement text = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是中间 frame 页面上的文字", text.getText());
break;
}else {
//返回frameset页面
driver.switchTo().defaultContent();
}
}
driver.switchTo().defaultContent();
driver.close();
}
}
public class Demo3 {
WebDriver driver; @BeforeMethod
public void Visitor(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} // 在指定元素上方进行鼠标悬浮,及点击悬浮后出现的菜单
@Test
public void roverOnElement() throws Exception {
driver.get("http://www.baidu.com");
Actions action = new Actions(driver);
// 在指定元素上进行鼠标悬浮
action.moveToElement(driver.findElement(By.name("tj_briicon"))).perform();
Thread.sleep(1000);
// 点击悬浮后出现的菜单
driver.findElement(By.linkText("糯米")).click();
;
driver.close();
} // 使用frame中的html源码内容来操作frame
@Test
public void testHandleFarme() {
driver.get("file:///F:/workspace/selenium_demo/src/main/webapp/frameset.html");
// 找到所有frame标签的内容
List<WebElement> frames = driver.findElements(By.tagName("frame"));
for (WebElement frame : frames) {
driver.switchTo().frame(frame);
// 判断frame页面源码中是否包含“中间 frame”
if (driver.getPageSource().contains("中间 frame")) {
// 找到页面P标签页面对象
WebElement text = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是中间 frame 页面上的文字", text.getText());
break;
} else {
// 返回frameset页面
driver.switchTo().defaultContent();
}
}
driver.switchTo().defaultContent();
driver.close();
} //操作iframe的页面元素
@Test
public void testHandleFarme2(){
driver.get("file:///F:/workspace/selenium_demo/src/main/webapp/frameset.html");
driver.switchTo().frame("leftframe");
//找到包含“这是iframe 页面上的文字”的元素对象
WebElement iframe = driver.findElement(By.tagName("iframe"));
//进入iframe页面区域
driver.switchTo().frame(iframe);
//在iframe页面找p标签的页面元素
WebElement p = driver.findElement(By.xpath("//p"));
Assert.assertEquals("这是iframe 页面上的文字", p.getText());
driver.close();
} //操作浏览器的cookie
@Test
public void testCookie(){
driver.get("http://www.baidu.com");
//得到当前页面下所有的cookie,并输出所在域、name、value、有效时期和路径
Set<Cookie> cookies = driver.manage().getCookies();
Cookie cookie = new Cookie("cookieName", "cookieValue");
System.out.println(String.format("Domain->name->value->expiry->path"));
for(Cookie cookie2 : cookies){
System.out.println(String.format(
"%s->%s->%s->%s->%s",
cookie2.getDomain(),
cookie2.getName(),
cookie2.getValue(),
cookie2.getExpiry(),
cookie2.getPath()
));
}
//删除cookie
//通过cookie的namen属性删除
driver.manage().deleteCookieNamed("cookieName");
//通过cookie对象删除
driver.manage().deleteCookie(cookie);
//删除全部cookie
driver.manage().deleteAllCookies();
}
}

Selenium WebDriver 常用API的更多相关文章

  1. Python+Selenium(webdriver常用API)

    总结了Python+selenium常用的一些方法函数,以后有新增再随时更新: 加载浏览器驱动: webdriver.Firefox() 打开页面:get() 关闭浏览器:quit() 最大化窗口:  ...

  2. Python Selenium 之常用API

    Selenium WebDriver下提供许多用来与浏览器.元素.鼠标.键盘.弹框.下拉菜单和列表的交互和设置方法.这些是计算机模拟人工进行自动化测试所必要依赖的方法.下面将用列表的方式总结出常用的A ...

  3. webdriver常用API

    本章涉及Selenium WebDriver的所有接口. Recommended Import Style 推荐的导入风格如下: from selenium import webdriver 然后,你 ...

  4. Selenium 3 常用 API

    元素定位 获取页面元素属性 元素判断 元素操作 操作输入框/单击 双击 下拉框操作 键盘操作 鼠标操作 单选框操作 多选框操作 拖动窗口 操作 JS 框 切换 frame 使用 JS 操作页面对象 操 ...

  5. selenium webdriver常用函数

    from selenium import webdriver driver = webdriver.Ie(executable_path = "e:\\IEDriverServer" ...

  6. selenium webdriver 常用断言

    断言常用的有: assertLocation(判断当前是在正确的页面). assertTitle(检查当前页面的title是否正确). assertValue(检查input的值, checkbox或 ...

  7. 转载 基于Selenium WebDriver的Web应用自动化测试

    转载原地址:  https://www.ibm.com/developerworks/cn/web/1306_chenlei_webdriver/ 对于 Web 应用,软件测试人员在日常的测试工作中, ...

  8. 【转】Selenium WebDriver + Python 环境

    转自:http://www.myext.cn/webkf/a_11878.html 1. 下载必要工具及安装包 1.1 [Python开发环境] 下载并安装Python 2.7.x版本 下载地址:ht ...

  9. Selenium WebDriver + Python 环境配置

    1.   下载必要工具及安装包 1.1.[Python开发环境] 下载并安装Python 2.7.x版本(当前支持2.x版本,不要下载最新的3.X的版本因为python3并非完全兼容python2) ...

随机推荐

  1. java_第一年_JDBC(7)

    Commons-dbutils是一个开源的JDBC工具类库,对JDBC进行封装,简化编码的工作量,包含的API: org.apache.commons.dbutils.QueryRunner org. ...

  2. CodeForces 877E DFS序+线段树

    CodeForces 877E DFS序+线段树 题意 就是树上有n个点,然后每个点都有一盏灯,给出初始的状态,1表示亮,0表示不亮,然后有两种操作,第一种是get x,表示你需要输出x的子树和x本身 ...

  3. 搜索(DFS)---矩阵中的连通分量数目

    矩阵中的连通分量数目 200. Number of Islands (Medium) Input: 11000 11000 00100 00011 Output: 3 题目描述:   给定一个矩阵,求 ...

  4. iOS 证书(.p12)和描述文件(.mobileprovision)的导出和使用方法

    为什么要导出.p12文件 当我们用大于三个mac设备开发应用时,想要申请新的证书,如果在我们的证书里,包含了3个发布证书,2个开发证书,可以发现再也申请不了开发证书和发布证书了(一般在我们的证书界面中 ...

  5. R语言抽样的问题

    基本抽样函数sample sample(x,size,replace=F/T) x是数据集, size规定了从对象中抽出多少个数 replace 为F时候,表示每次​抽取后的数就不能在下一次被抽取:T ...

  6. python基础--文件的操作

    #r w a 文件读取操作 默认打开为读操作 #f=open('coldplay.txt','r',encoding="utf-8")#open函数默认已系统编码方式打开windo ...

  7. [python 学习] 编码

    一.源文件编码(encoding: utf-8) 1. python 2.x 默认按ascii编码读取源文件,源码中出现了ascii不能表示的字符 "的",所以报错(3.x版本不报 ...

  8. 去除重复嵌套的html标签函数

    去除重复嵌套的html标签 function strip_multi_tags($str, $tag = 'div'){ preg_match_all('/<'.$tag.'>|<\ ...

  9. pycharm中能运行,但是往往py都要放到服务器上去跑,问题来了

    py文件在linux上运行,导包错误: 在py文件中添加项目的根目录: import sys sys.path.append('项目路径') sys.path.append(os.path.dirna ...

  10. bzoj2325 [ZJOI2011]道馆之战 树链剖分+DP+类线段树最大字段和

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=2325 题解 可以参考线段树动态维护最大子段和的做法. 对于线段树上每个节点 \(o\),维护 ...