Skip to content

Selenium - 用户交互

Selenium WebDriver 允许你模拟与网页元素的多种用户交互。这些交互涵盖了从点击和输入等基本操作,到拖放或键盘快捷键等更复杂的动作。

大多数常见的交互都是直接在 WebElement 对象上执行的:

  • 输入文本: 对输入字段和文本区域使用 sendKeys()。
  • 点击: 对按钮、链接、单选按钮、复选框等使用 click()。
  • 清空文本: 在输入前使用 clear() 移除输入字段中的现有文本。
  • 提交表单: 对表单内的任何元素使用 submit(),或者直接点击提交按钮。即使元素不是按钮,submit() 也有效。
WebElement usernameInput = driver.findElement(By.id("username"));
WebElement passwordInput = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginBtn"));
usernameInput.clear();
usernameInput.sendKeys("testuser");
passwordInput.clear();
passwordInput.sendKeys("securePassword");
loginButton.click(); // 或 passwordInput.submit();

对于标准的 HTML <select> 元素,Selenium 提供了专门的 Select 类,以便更方便地进行交互:

import org.openqa.selenium.support.ui.Select;
WebElement countryDropdownElement = driver.findElement(By.id("countrySelect"));
Select countrySelect = new Select(countryDropdownElement);
// 按可见文本选择
countrySelect.selectByVisibleText("United States");
// 按 <option> 标签的 value 属性选择
countrySelect.selectByValue("US");
// 按索引选择(基于 0)
countrySelect.selectByIndex(1);

Select 类还提供了用于取消选择选项的方法 (deselectBy...()、deselectAll()) 以及获取已选择选项的方法 (getFirstSelectedOption()、getAllSelectedOptions())。

对于更复杂的交互,如鼠标移动、拖放、键盘修饰键 (Shift, Ctrl, Alt) 和上下文点击(右键点击),WebDriver 提供了 Actions 类。你可以构建一系列动作,然后调用 perform() 来执行它们。

import org.openqa.selenium.interactions.Actions;
Actions actions = new Actions(driver);
WebElement mainMenu = driver.findElement(By.id("mainMenu"));
WebElement subMenu = driver.findElement(By.id("subMenuLink"));
actions.moveToElement(mainMenu).perform(); // 悬停在主菜单上
// 如果需要等待子菜单出现,可以在此处添加一个短时等待
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOf(subMenu));
subMenu.click(); // 点击子菜单项
WebElement sourceElement = driver.findElement(By.id("draggable"));
WebElement targetElement = driver.findElement(By.id("droppable"));
actions.dragAndDrop(sourceElement, targetElement).perform();
WebElement elementToRightClick = driver.findElement(By.id("contextMenuArea"));
actions.contextClick(elementToRightClick).perform();
// 添加与出现的上下文菜单交互的步骤
WebElement item1 = driver.findElement(By.id("item1"));
WebElement item3 = driver.findElement(By.id("item3"));
// 使用 SHIFT 键选择多个项目
actions.click(item1)
.keyDown(Keys.SHIFT) // 按下 Shift
.click(item3) // 点击第二个项目
.keyUp(Keys.SHIFT) // 松开 Shift
.perform();

Actions 类还提供了许多其他方法,如 doubleClick()、clickAndHold()、release()、sendKeys(Keys.chord(Keys.CONTROL, "a")) 等。有关完整列表,请参阅 Selenium 文档。

现代 Web 应用程序通常会动态加载内容。直接与尚未加载的元素进行交互会导致你的脚本失败。Selenium 提供了**等待(Waits)**来处理这种同步问题。使用适当的等待对于稳定的测试至关重要。这将在 ‘Selenium - Waits’ 章节中详细介绍。