Java 获取 Select 元素数据 (不使用表单)
您可以使用 Java 中的 WebElement 对象和 Select 类来获取 select (option) 中的数据。以下是一个示例代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class SelectOptionExample {
public static void main(String[] args) {
// 设置Chrome驱动程序路径
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// 实例化Chrome浏览器驱动程序
WebDriver driver = new ChromeDriver();
// 导航到测试页面
driver.get("http://example.com/test.html");
// 定位select元素
WebElement selectElement = driver.findElement(By.id("selectElementId"));
// 实例化Select对象
Select select = new Select(selectElement);
// 获取所有选项
List<WebElement> options = select.getOptions();
// 循环打印选项文本
for (WebElement option : options) {
System.out.println(option.getText());
}
// 选择指定选项
select.selectByVisibleText('Option 2');
// 关闭浏览器驱动程序
driver.quit();
}
}
在此示例中,我们首先使用 WebDriver 对象的 findElement 方法查找 select 元素,然后将其传递给 Select 类的构造函数,以创建一个 Select 对象。然后,我们可以使用 Select 对象的 getOptions 方法获取所有选项,或使用 selectByVisibleText 方法选择指定选项。
原文地址: https://www.cveoy.top/t/topic/nzoW 著作权归作者所有。请勿转载和采集!