1. 文本框Textbox
// Find the username input element by its name
WebElement username = driver.findElement(By.name("username"));
// Enter the user name: jill
username.clear();
username.sendKeys("jill");
// Find the password input element by its name
WebElement password = driver.findElement(By.name("password"));
// Enter the password:123456
password.clear();
password.sendKeys("123456");
2. 按钮Button
// Click the Login button by className
WebElement loginButton = driver.findElement(By.className("btnTile"));
loginButton.click();
3. 下拉框Select
//通过id或者name来定位下拉框, new一个Select对象
Select globalSelect = new Select(driver.findElement(By.id("selectid")));
//通过选项索引选中第二项
globalSelect.selectByIndex(1); --[注]index是从0开始的
//通过下拉选项的内容选中第二项(second_item)
globalSelect.selectByVisibleText("second_item");
//遍历Select下拉列表的选项
WebElement select = driver.findElement(By.tagName("select"));
List
for (WebElement option : myOptions) {
System.out.println(option.getAttribute("value");
option.click();
}
4. 对话框Alert, Confirm, Prompt
//捕获Alert/Confirm/Prompt对话框
Alert alert = driver.switchTo().alert();
//获得Alert/Confirm/Prompt对话框内容
String alertText = alert.getText();
//确认Alert/Confirm/Prompt
alert.accept();
//取消Alert/Confirm/Prompt
alert.dismiss();
//输入值到Prompt
prompt.sendKeys("abc");
5. 弹出窗口 popup window
//使用driver.switchTo()可以进行Windows, Frames, Alerts, Confirms, Prompts之间的切换
driver.switchTo().window("windowhandle");
driver.switchTo().frame("framename");
driver.switchTo().alert();
6. 切换到新的Window (import java.util.Set;)
//1. 保存之前的Windows Handles
Set
String beforeHandler = beforeHandlers.iterator().next();
// 2. 执行弹出新窗口的操作
WebElement OKButton = driver.findElement(By.name("OK"));
OKButton.click();
//3. 保存现在的Windows Handles
Set
//4. 从现在的Windows Handles中remove调之前的,就能得到刚弹出新窗口的window handle
afterHandlers.removeAll(beforeHandlers);
String newWinhandler = afterHandlers.iterator().next();
//5. 切换到新弹出的窗口
driver.switchTo().window(newWinhandler);
//6. 返回之前的窗口
driver.switchTo().window(beforeHandler);
7. 上传文件
WebElement FileUpload =driver.findElement(By.name("fileupload"));
String filePath = "C:\\myFile01";
earFileUpload.sendKeys(filePath);