selenium_element_interaction
Selenium - 元素交互操作
Section titled “Selenium - 元素交互操作”一旦你使用定位器策略(findElement 或 findElements)定位到了一个 WebElement(表示网页上的一个元素),你就可以对它执行各种操作或从中检索信息。Selenium WebDriver 提供了一系列丰富的方法,用于与常见的网页元素进行交互,例如文本框、按钮、复选框、单选按钮、下拉列表等。
本节涵盖了与标准 HTML 元素的常见交互操作。
常见元素交互
Section titled “常见元素交互”最常见的操作是点击。这适用于按钮、链接、单选按钮、复选框,有时也适用于其他元素,如 div 或 img,如果它们绑定了点击事件处理器。
// Locate a submit button and click itWebElement submitButton = driver.findElement(By.id("submit-btn"));submitButton.click();
// Locate a link and click itWebElement profileLink = driver.findElement(By.linkText("My Profile"));profileLink.click();输入文本(输入框和文本区域)
Section titled “输入文本(输入框和文本区域)”使用 sendKeys() 方法模拟向文本输入字段或文本区域输入文本。
// Locate a username input fieldWebElement usernameInput = driver.findElement(By.name("username"));
// Type text into the fieldusernameInput.sendKeys("testuser");
// You can also send special keys// import org.openqa.selenium.Keys;// usernameInput.sendKeys(Keys.TAB); // Simulate pressing the Tab key在输入新文本之前,使用 clear() 方法移除输入字段或文本区域中任何已有的文本。
WebElement searchBox = driver.findElement(By.id("search"));
// Clear any existing textsearchBox.clear();
// Enter a new search termsearchBox.sendKeys("Selenium WebDriver");你可以直接 click() 提交按钮,或者如果你的焦点在表单中的一个元素(如输入字段)上,你可以在该元素上调用 submit() 方法。submit() 方法会找到包含该元素的表单并提交它。
WebElement passwordInput = driver.findElement(By.id("password"));passwordInput.sendKeys("secret");
// Option 1: Click the submit button (preferred if button exists)// WebElement loginButton = driver.findElement(By.id("login-button"));// loginButton.click();
// Option 2: Submit from an element within the formpasswordInput.submit();处理复选框和单选按钮
Section titled “处理复选框和单选按钮”你可以 click() 它们来选择/取消选择。你也可以使用 isSelected() 检查它们的当前状态。
// Locate a checkboxWebElement newsletterCheckbox = driver.findElement(By.id("subscribe-news"));
// Check if it's already selectedif (!newsletterCheckbox.isSelected()) { System.out.println("Checkbox not selected, clicking it..."); newsletterCheckbox.click();}
// Locate a radio buttonWebElement femaleRadioButton = driver.findElement(By.cssSelector("input[type='radio'][value='female']"));
// Select it if not already selectedif (!femaleRadioButton.isSelected()) { femaleRadioButton.click();}处理下拉列表(Select 元素)
Section titled “处理下拉列表(Select 元素)”对于标准的 HTML <select> 下拉列表,Selenium 提供了一个专门的 Select 类(位于 org.openqa.selenium.support.ui.Select 中),它简化了交互。
// Import the Select class// import org.openqa.selenium.support.ui.Select;
// Locate the <select> elementWebElement countryDropdownElement = driver.findElement(By.id("country"));
// Create a Select objectSelect countrySelect = new Select(countryDropdownElement);
// Select an option by its visible textcountrySelect.selectByVisibleText("Canada");
// Wait a bit to see the selection (replace with explicit wait in real tests)// try { Thread.sleep(2000); } catch (InterruptedException e) {}
// Select an option by its value attribute// Example: <option value="US">United States</option>countrySelect.selectByValue("US");
// Wait a bit// try { Thread.sleep(2000); } catch (InterruptedException e) {}
// Select an option by its index (0-based)countrySelect.selectByIndex(0); // Selects the first option
// Get the currently selected optionWebElement selectedOption = countrySelect.getFirstSelectedOption();System.out.println("Selected option: " + selectedOption.getText());
// Get all optionsjava.util.List<WebElement> allOptions = countrySelect.getOptions();System.out.println("Total options: " + allOptions.size());注意:如果下拉列表是使用自定义元素(如 <div> 和 <ul>)实现的,则不能使用 Select 类。你需要点击该元素以打开下拉列表,然后使用标准定位器点击所需的选项元素。
从元素中获取信息
Section titled “从元素中获取信息”使用 getText() 获取元素的可见文本内容(用户看到的内容)。
// Locate a paragraph or headingWebElement messageElement = driver.findElement(By.id("welcome-message"));String message = messageElement.getText();System.out.println("Welcome message: " + message);使用 getAttribute("attributeName") 获取特定 HTML 属性的值(例如 href, src, value, class, style)。
// Locate a linkWebElement docsLink = driver.findElement(By.linkText("Documentation"));String linkUrl = docsLink.getAttribute("href");System.out.println("Docs link URL: " + linkUrl);
// Get the value typed into an input boxWebElement nameInput = driver.findElement(By.id("name"));nameInput.sendKeys("Test Name");String enteredValue = nameInput.getAttribute("value");System.out.println("Value in input: " + enteredValue);检查元素状态
Section titled “检查元素状态”你可以检查元素当前是否显示、是否启用或是否被选中。
WebElement loginButton = driver.findElement(By.id("login"));WebElement rememberMeCheckbox = driver.findElement(By.id("remember"));
// Is the button visible on the page?boolean isDisplayed = loginButton.isDisplayed();System.out.println("Login button displayed: " + isDisplayed);
// Is the button clickable?boolean isEnabled = loginButton.isEnabled();System.out.println("Login button enabled: " + isEnabled);
// Is the checkbox checked? (Returns false if not selected)boolean isSelected = rememberMeCheckbox.isSelected();System.out.println("Remember me selected: " + isSelected);这些基本交互构成了大多数 WebDriver 脚本的核心。将这些操作与适当的等待(waits)和断言(assertions)结合起来,可以自动化复杂的用例流程。