Java+selenium之WebDriver页面元素的操作(三)

时间:2023-03-08 19:14:17
Java+selenium之WebDriver页面元素的操作(三)

1. 输入框(text field or textarea)

 WebElement we = driver.findElement(By.id("id"));
//将输入框清空
we.clear();
// 在输入框中输入内容
we.sendKeys(“test”);
// 获取输入框的文本内容, 取得就是 value 属性的值
element.getAttribute("value");

2. 下拉选择框(select)

 // 找到下拉选择框的元素
Select select = new Select(driver.findElement(By.id("id")));
// 选择对应的选择项
select.selectByVisibleText(“ 北京市 ”); // 通过可见文本去选择
select.selectByValue(“beijing”); // 通过 html 标签中的 value 属性值去选择
select.selectByIndex(1); // 通过 index(索引从0开始)选择
// 不选择对应的选择项
select.deselectAll();
select.deselectByValue(“ 替换成实际的值 ”);
select.deselectByVisibleText(“ 替换成实际的值 ”);
// 获取所有选择项的值
List<WebElement> wes = select.getAllSelectedOptions();
// 获取第一个选择项或者默认选择项
String text = select.getFirstSelectedOption().getText();

3. 单选框(Radio Button)

 // 找到单选框元素
WebElement we =driver.findElement(By.id("id"));
// 选择某个单选项
we.click();
// 清空某个单选项
we.clear();
// 判断某个单选项是否已经被选择, 返回的是 Boolean 类型
we.isSelected();

4. 多选框(Checkbox)

 // 找到多选框元素
WebElement checkbox = driver.findElement(By.id("id"));
// 点击复选框
checkbox.click();
// 清除复选
checkbox.clear();
// 判断复选框是否被选中
checkbox.isSelected();
// 判断复选框是否可用
checkbox.isEnabled(); 

5. 按钮(Button)

 // 找到按钮元素
WebElement saveButton = driver.findElement(By.id("id"));
// 点击按钮
saveButton.click();
// 判断按钮是否可用
saveButton.isEnabled ();

6. 左右选择框

 // 左边是可供选择项,选择后移动到右边的框中,反之亦然,先处理选择框
Select lang = new Select(driver.findElement(By.id("languages")));
lang.selectByVisibleText(“English”);
// 再处理向右移动的按钮
WebElement addLanguage = driver.findElement(By.id("addButton"));
addLanguage.click();

7. 弹出对话框(Popup dialogs)

 // 切换到弹出框
Alert alert = driver.switchTo().alert();
// 确定
alert.accept();
// 取消或者点"X"
alert.dismiss();
// 获取弹出框文本内容
alert.getText();

8. 表单(Form)

 // 只适合表单的提交
driver.findElement(By.id("approve")).submit();

9. 上传文件 (Upload File)

 // 定位上传控件
WebElement adFileUpload = driver.findElement(By.id("id"));
// 定义了一个本地文件的路径
String filePath = "C:\\test\\uploadfile\\test.jpg";
// 为上传控件进行赋值操作,将需要上传的文件的路径赋给控件
adFileUpload.sendKeys(filePath);

10. 拖拉(Drag and Drop)

 // 定义第一个元素
WebElement element =driver.findElement(By.name("source"));
// 定义第二个元素
WebElement target = driver.findElement(By.name("target"));
// 将第一个元素拖拽到第二个元素
(new Actions(driver)).dragAndDrop(element, target).perform();

11. 鼠标悬停(Mouse MoveOn)

 Actions builder = new Actions(driver);
builder.moveToElement(driver.findElement(By.id("id"))).perform();