selenium

本文详细介绍了Selenium在自动化测试中的应用,包括自动化测试步骤、获取页面元素个数、执行JavaScript、数据校验、清除输入框内容、等待方式、处理对话框、遍历元素等。还讲解了如何使用Selenium的get_attribute方法、处理select下拉框、模拟鼠标键盘操作、截图等功能,是Selenium测试的重要参考资料。

自动化测试的步骤

1 找到web页面的元素

2 对页面元素的对象进行操作,例如:点击链接、在输入框输入字符

3 验证页面上的元素是否符合预期

寻找元素的顺序:id  cssSelector  xpath

Selenium获取页面指定元素个数

1 因下拉框的tagname属性值为select,可通过获取标签为select的元素来获取下拉框个数

List<WebElement> elements = driver.findElements(By.tagName("select"));
int number=elements.size();
Assert.assertEquals(number,12);//验证是否为12

2 因下拉框默认显示“请选择”,可通过获取页面的“请选择”元素来获取下拉框个数。

List<WebElement> elements = driver.findElements(By.xpath("//*[text()='请选择']"));
int number=elements.size();
Assert.assertEquals(number,12);//验证是否为12

 

执行js脚本

((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");

//滑动纵向滚动条到底部,与元素一齐
            JavascriptExecutor JS=(JavascriptExecutor) driver;
            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", input_btn);

最大化窗口   webDriver.manage().window().maximize();

selenium get_attribute的几种用法

getAttribute(‘textContent’)会获取图内的"文章管理"文字

获取元素内的全部HTML:getAttribute('innerHTML')

获取包含选中元素的HTML:getAttribute('outerHTML')

获取input里面的value值:driver.findElement(By.id("confirm_email_to_download")).getAttribute("value")

Selenium获取input值的两种方法:WebElement.getAttribute("value")和WebElement.getText()

WebElement ordercode_btn=driver.findElement(By.xpath("//table/tbody/tr[1]/td[2]/div/a"));
String ordercode=ordercode_btn.getText();

<span id="current-selection">Acxiom</span>

driver.findElement(By.cssSelector("span#current-selection")).getText()

数据校验

String success="zxj自动化测试";
 if(text.getText().contains(success)){
            System.out.println("<-成品仓--添加部件成功!->");
 }

if(ordercode.equals(serachresult.getText())){
            System.out.println("<---成品仓--成品标签订单筛选成功!---->");
        }
 

清除输入框里面的内容

WebElement emailInputBox = driver.findElement(By.id("user"));

emailInputBox.click();
emailInputBox.clear();
emailInputBox.sendKeys(userName);

 

三种等待方式

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait

利用WebDriverWait类和ExpectedCondition接口就能实现这一点

1 显示等待

显示等待是针对于某个特定的元素设置的等待时间,如果在规定的时间范围内,没有找到元素,则会抛出异常,如果在规定的时间内找到了元素,则直接执行,即找到元素就执行相关操作。默认检测频率为0.5s,默认抛出异常为:NoSuchElementException

#WebDriverWait()方法使用
element=WebDriverWait(driver, 10).until(lambda driver : driver.find_element_by_id("kw"))        
element.send_keys("selenium")  

import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait(driver, 10,1).until(ExpectedConditions.presenceOfElementLocated(By.linkText("退出")));

每隔1秒去调用一下until中的函数,默认是0.5秒,如果等待10秒还没有找到元素 。则抛出异常。

2 隐式等待

隐式等待一个元素被发现,或一个命令完成。如果超出了设置时间的则抛出异常。

隐式等待是设置的全局等待,分为1、页面加载超时等待 ;2、页面元素加载超时;3、异步脚本超时

如果是页面元素超时,设置等待时间,是对页面中的所有元素设置加载时间。隐式等待是其实可以理解成在规定的时间范围内,浏览器在不停的刷新页面,直到找到相关元素或者时间结束。

driver.implicitlyWait(30)       等待30秒加载不出来就会抛出异常,10秒内加载出来正常返回

driver.find_element_by_id("su").click()

dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

title_is 标题是某内容
title_contains 标题包含某内容
presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p')
visibility_of_element_located 元素可见,传入定位元组
visibility_of 可见,传入元素对象
presence_of_all_elements_located 所有元素加载出
text_to_be_present_in_element 某个元素文本包含某文字
text_to_be_present_in_element_value 某个元素值包含某文字
frame_to_be_available_and_switch_to_it frame加载并切换
invisibility_of_element_located 元素不可见
element_to_be_clickable 元素可点击
staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
element_to_be_selected 元素可选择,传元素对象
element_located_to_be_selected 元素可选择,传入定位元组
element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
alert_is_present 是否出现Alert

引入文件

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

(1)页面元素是否在页面上可用和可被单击:elementToBeClickable(By locator)

(2)页面元素处于被选中状态:elementToBeSelected(WebElement element)

(3)页面元素在页面中存在:presenceOfElementLocated(By locator)

(4)在页面元素中是否包含特定的文本:textToBePresentInElement(By locator)

(5)页面元素值:textToBePresentInElementValue(By locator, java.lang.String text)

(6)标题 (title):titleContains(java.lang.String title)

窗口的句柄

//得到当前窗口的句柄
String currentWindow = dr.getWindowHandle();
//得到所有窗口的句柄
Set<String> handles = dr.getWindowHandles();

捕捉到窗口

dr.switchTo.window()

Set<String> allWindowsId = driver.getWindowHandles();
 for (String windowId : allWindowsId) {
       if (driver.switchTo().window(windowId).getTitle().contains("op")) {
             driver.switchTo().window(windowId);
              break;
           }
      }

 

selenium三种断言以及异常类型

Assert 失败时,该测试将终止。
Verify 失败时,该测试将继续执行,并将错误记入日显示屏 。也就是说允许此单个 验证通过。确保应用程序在正确的页面上
Waitfor 用于等待某些条件变为真。可用于 AJAX 应用程序的测试。

验证和断言的区别:验证失败后不影响脚本的继续执行,断言失败后将停止脚本的执行。

assertTitle(检查当前页面的title是否正确)、
assertValue(检查 input 的值, checkbox 或 radio,有值为”on”无为”off”)、

assertText(检查指定元素的文本)、

assertAttribute(检查当前指定元素的属性的值)、

verifyTitle (检查预期的页面标题)

verifyText(核实预期的文本和相应的HTML标签是否都存在于页面上)

异常类型

AssertionError:assert语句失败

AttributeError:试图访问一个对象没有的属性

IOError:输入输出异常,基本是无法打开文件

ImportError:无法引入模块或者包,基本是路径问题

IndentationError:语法错误,代码没有正确的对齐

IndexError:下标索引超出序列边界

KeyError:试图访问字典里不存在的键

KeyboadrInterrupt:Ctrl+c被按下

NameError:使用一个还未赋值对象的变量

SyntaxError:python代码逻辑语法错误,不能执行

TypeError:传入的对象类型与要求不符

UnboundLocalError:试图访问一个还未设置的全局变量,基本上是由于另有一个同名的全局变量,导致你以为在访问

ValueError:传入一个不被期望的值,即使类型正确

如何利用selenium-webdriver截图

File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShotFile, new File("D:/test.png"));}}

利用Actions类模拟鼠标和键盘的操作

这个actions类,主要定义了一些模拟用户的鼠标mouse,键盘keyboard操作。对于这些操作,使用perform()
方法进行执行。
actions类可以完成单一的操作,也可以完成几个操作的组合

//新建一个action
Actions action=new Actions(driver);
//操作
WebElement element=dr.findElement(By.id("test"));
WebElement element1=dr.findElement(By.id("su"));
action.sendKeys(element,"test").perform();
action.moveToElement(element1);
action.click().perform()

 

如何操作select下拉框

Select selectAge = new Select(dr.findElement(By.id("User_Age")));
selectAge.selectByIndex(2);     通过下拉列表中选项的索引选中第二项,

selectShen.selectByValue("上海");   通过下拉列表中的选项的value属性选中"上海"这一项

selectTown.selectByVisibleText("浦东");  通过下拉列表中选项的可见文本选 中"浦东"这一项

Select selectCity = new Select(dr.findElement(By.id("User_City")));
for(WebElement e : selectCity.getOptions())
e.click();                                                  想遍历一下下拉列表所有选项,用click进行选中选项

 

如何处理alerm confirm  prompt对话框

dr.switchTo().alert();      这句可以得到alert\confirm\prompt对话框的对象

Alert alert = dr.switchTo().alert();

String text = alert.getText();
System.out.println(text);
alert.dismiss();

confirm.accept();

 

getText() 得到它的文本值
accept() 相当于点击它的"确认"
dismiss() 相当于点击"取消"或者叉掉对话框
sendKeys() 输入值,这个alert\confirm没有对话框就不能用了,不然会报错

for循环

//定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的值
WebElement element = driver.findElement(By.className("login"));
List<WebElement>  el = element.findElements(By.tagName("label"));
for(WebElement e : el){
    System.out.println(e.getText());

}

//定位到所有<input>标签的元素,然后输出他们的id
List<WebElement> element = driver.findElements(By.tagName("input"));
for (WebElement e : element){
    System.out.println(e.getAttribute("id"));
}

findElement返回一个元素对象,如果没有找到就抛出异常 NoElementFindException()

findElements返回符合条件的元素List,如果不存在符合条件的就返回一个空的list

driver.findElement(By.className(className))
By.cssSelector(selector)
By.id(id)
By.linkText(linkText)
By.name(name)
By.partialLinkText(linkText)
By.tagName(name)
By.xpath(xpathExp)

遍历出需要的输入框

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值