java selenium 常见web UI 元素操作及API使用
本篇介绍我们如何利用selenium来操作各种页面元素
阅读目录
- 链接(link)
- 输入框textbox
- 按钮(Button)
- 下拉选择框(Select)
- 单选按钮(RadioButton)
- 多选框checkbox
链接(link)
<div> <p>链接link</p> <ahref="www.cnblogs.com/tankxiao">小坦克</a> </div>
链接的操作
//找到链接元素
WebElementlink1=driver.findElement(By.linkText("小坦克"));
WebElementlink11=driver.findElement(By.partialLinkText("坦克"));
//点击链接
link1.click();
输入框textbox
<div> <p>输入框testbox</p> <inputtype="text"id="usernameid"value="username"/> </div>
输入框的操作
//找到元素
WebElementelement=driver.findElement(By.id("usernameid"));
//在输入框中输入内容
element.sendKeys("test111111");
//清空输入框
element.clear();
//获取输入框的内容
element.getAttribute("value");
按钮(Button)
<div> <p>按钮button</p> <inputtype="button"value="添加"id="proAddItem_0"/> </div>
找到按钮元素
//找到按钮元素 Stringxpath="//input[@value='添加']"; WebElementaddButton=driver.findElement(By.xpath(xpath)); //点击按钮 addButton.click(); //判断按钮是否enable addButton.isEnabled();
下拉选择框(Select)
<div> <p>下拉选择框框Select</p> <selectid="proAddItem_kind"name="kind"> <optionvalue="1">电脑硬件</option> <optionvalue="2">房产</option> <optionvalue="18">种类AA</option> <optionvalue="19">种类BB</option> <optionvalue="20">种类BB</option> <optionvalue="21">种类CC</option> </select> </div>
下拉选择框的操作
//找到元素
Selectselect=newSelect(driver.findElement(By.id("proAddItem_kind")));
//选择对应的选择项,index从0开始的
select.selectByIndex(2);
select.selectByValue("18");
select.selectByVisibleText("种类AA");
//获取所有的选项
List<WebElement>options=select.getOptions();
for(WebElementwebElement:options){
System.out.println(webElement.getText());
}
单选按钮(RadioButton)
<div> <p>单选项RadioButton</p> <inputtype="radio"value="Apple"name="fruit>"/>Apple <inputtype="radio"value="Pear"name="fruit>"/>Pear <inputtype="radio"value="Banana"name="fruit>"/>Banana <inputtype="radio"value="Orange"name="fruit>"/>Orange </div>
单选项元素的操作
//找到单选框元素
Stringxpath="//input[@type='radio'][@value='Apple']";
WebElementapple=driver.findElement(By.xpath(xpath));
//选择某个单选框
apple.click();
//判断某个单选框是否已经被选择
booleanisAppleSelect=apple.isSelected();
//获取元素属性
apple.getAttribute("value");
多选框checkbox
<div> <p>多选项checkbox</p> <inputtype="checkbox"value="Apple"name="fruit>"/>Apple <inputtype="checkbox"value="Pear"name="fruit>"/>Pear <inputtype="checkbox"value="Banana"name="fruit>"/>Banana <inputtype="checkbox"value="Orange"name="fruit>"/>Orange </div>
多选框的操作和单选框一模一样的,这里就不再讲了。
以上就是javaselenium常见webUI元素操作的资料整理,后续继续补充,谢谢大家对本站的支持!