Selenium的核心库试图提供底层以及普适的功能. 每种语言的支持类都为常见交互提供特定的包装器, 可用于简化某些行为.
Support features
1 - 期望状态的等待
期望状态与 显示等待 一起使用. 与其定义要使用 lambda 执行的代码块, 不如使用 lambda 执行可以创建 Conditions 方法来表示等待的常见事物. 有些方法将定位器作为参数, 有些方法将元素作为参数.
这些方法可以包括以下条件:
- 元素存在
- 元素已过期
- 元素可见
- 文本可见
- 标题包含特定值
2 - 命令监听器
允许您在每次发送特定 Selenium 命令时执行自定义操作
3 - 同颜色一起工作
在测试中, 您偶尔会需要验证某事物的颜色;问题是网络上的颜色定义不是个常量. 如果有一种简单的方法可以比较颜色的十六进制与RGB呈现, 或者颜色的RGBA与HSLA呈现, 岂不美哉?
不用担心有一个解决方案:Color 类!
首先, 您需要导入该类:
import org.openqa.selenium.support.Color;
from selenium.webdriver.support.color import Color
// This feature is not implemented - Help us by sending a pr to implement this feature
include Selenium::WebDriver::Support
// This feature is not implemented - Help us by sending a pr to implement this feature
import org.openqa.selenium.support.Color
您现在可以开始创建颜色对象. 每个颜色对象都需要使用您颜色的字符串定义来创建. 支持的颜色定义如下:
private final Color HEX_COLOUR = Color.fromString("#2F7ED8");
private final Color RGB_COLOUR = Color.fromString("rgb(255, 255, 255)");
private final Color RGB_COLOUR = Color.fromString("rgb(40%, 20%, 40%)");
private final Color RGBA_COLOUR = Color.fromString("rgba(255, 255, 255, 0.5)");
private final Color RGBA_COLOUR = Color.fromString("rgba(40%, 20%, 40%, 0.5)");
private final Color HSL_COLOUR = Color.fromString("hsl(100, 0%, 50%)");
private final Color HSLA_COLOUR = Color.fromString("hsla(100, 0%, 50%, 0.5)");
HEX_COLOUR = Color.from_string('#2F7ED8')
RGB_COLOUR = Color.from_string('rgb(255, 255, 255)')
RGB_COLOUR = Color.from_string('rgb(40%, 20%, 40%)')
RGBA_COLOUR = Color.from_string('rgba(255, 255, 255, 0.5)')
RGBA_COLOUR = Color.from_string('rgba(40%, 20%, 40%, 0.5)')
HSL_COLOUR = Color.from_string('hsl(100, 0%, 50%)')
HSLA_COLOUR = Color.from_string('hsla(100, 0%, 50%, 0.5)')
// This feature is not implemented - Help us by sending a pr to implement this feature
HEX_COLOUR = Color.from_string('#2F7ED8')
RGB_COLOUR = Color.from_string('rgb(255, 255, 255)')
RGB_COLOUR = Color.from_string('rgb(40%, 20%, 40%)')
RGBA_COLOUR = Color.from_string('rgba(255, 255, 255, 0.5)')
RGBA_COLOUR = Color.from_string('rgba(40%, 20%, 40%, 0.5)')
HSL_COLOUR = Color.from_string('hsl(100, 0%, 50%)')
HSLA_COLOUR = Color.from_string('hsla(100, 0%, 50%, 0.5)')
// This feature is not implemented - Help us by sending a pr to implement this feature
private val HEX_COLOUR = Color.fromString("#2F7ED8")
private val RGB_COLOUR = Color.fromString("rgb(255, 255, 255)")
private val RGB_COLOUR_PERCENT = Color.fromString("rgb(40%, 20%, 40%)")
private val RGBA_COLOUR = Color.fromString("rgba(255, 255, 255, 0.5)")
private val RGBA_COLOUR_PERCENT = Color.fromString("rgba(40%, 20%, 40%, 0.5)")
private val HSL_COLOUR = Color.fromString("hsl(100, 0%, 50%)")
private val HSLA_COLOUR = Color.fromString("hsla(100, 0%, 50%, 0.5)")
Color类还支持在以下网址中指定的所有基本颜色定义 http://www.w3.org/TR/css3-color/#html4.
private final Color BLACK = Color.fromString("black");
private final Color CHOCOLATE = Color.fromString("chocolate");
private final Color HOTPINK = Color.fromString("hotpink");
BLACK = Color.from_string('black')
CHOCOLATE = Color.from_string('chocolate')
HOTPINK = Color.from_string('hotpink')
// This feature is not implemented - Help us by sending a pr to implement this feature
BLACK = Color.from_string('black')
CHOCOLATE = Color.from_string('chocolate')
HOTPINK = Color.from_string('hotpink')
// This feature is not implemented - Help us by sending a pr to implement this feature
private val BLACK = Color.fromString("black")
private val CHOCOLATE = Color.fromString("chocolate")
private val HOTPINK = Color.fromString("hotpink")
如果元素上未设置颜色, 则有时浏览器会返回“透明”的颜色值. Color类也支持此功能:
private final Color TRANSPARENT = Color.fromString("transparent");
TRANSPARENT = Color.from_string('transparent')
// This feature is not implemented - Help us by sending a pr to implement this feature
TRANSPARENT = Color.from_string('transparent')
// This feature is not implemented - Help us by sending a pr to implement this feature
private val TRANSPARENT = Color.fromString("transparent")
现在, 您可以安全地查询元素以获取其颜色/背景色, 任何响应都将被正确解析并转换为有效的Color对象:
Color loginButtonColour = Color.fromString(driver.findElement(By.id("login")).getCssValue("color"));
Color loginButtonBackgroundColour = Color.fromString(driver.findElement(By.id("login")).getCssValue("background-color"));
login_button_colour = Color.from_string(driver.find_element(By.ID,'login').value_of_css_property('color'))
login_button_background_colour = Color.from_string(driver.find_element(By.ID,'login').value_of_css_property('background-color'))
// This feature is not implemented - Help us by sending a pr to implement this feature
login_button_colour = Color.from_string(driver.find_element(id: 'login').css_value('color'))
login_button_background_colour = Color.from_string(driver.find_element(id: 'login').css_value('background-color'))
// This feature is not implemented - Help us by sending a pr to implement this feature
val loginButtonColour = Color.fromString(driver.findElement(By.id("login")).getCssValue("color"))
val loginButtonBackgroundColour = Color.fromString(driver.findElement(By.id("login")).getCssValue("background-color"))
然后, 您可以直接比较颜色对象:
assert loginButtonBackgroundColour.equals(HOTPINK);
assert login_button_background_colour == HOTPINK
// This feature is not implemented - Help us by sending a pr to implement this feature
assert(login_button_background_colour == HOTPINK)
// This feature is not implemented - Help us by sending a pr to implement this feature
assert(loginButtonBackgroundColour.equals(HOTPINK))
或者, 您可以将颜色转换为以下格式之一并执行静态验证:
assert loginButtonBackgroundColour.asHex().equals("#ff69b4");
assert loginButtonBackgroundColour.asRgba().equals("rgba(255, 105, 180, 1)");
assert loginButtonBackgroundColour.asRgb().equals("rgb(255, 105, 180)");
assert login_button_background_colour.hex == '#ff69b4'
assert login_button_background_colour.rgba == 'rgba(255, 105, 180, 1)'
assert login_button_background_colour.rgb == 'rgb(255, 105, 180)'
// This feature is not implemented - Help us by sending a pr to implement this feature
assert(login_button_background_colour.hex == '#ff69b4')
assert(login_button_background_colour.rgba == 'rgba(255, 105, 180, 1)')
assert(login_button_background_colour.rgb == 'rgb(255, 105, 180)')
// This feature is not implemented - Help us by sending a pr to implement this feature
assert(loginButtonBackgroundColour.asHex().equals("#ff69b4"))
assert(loginButtonBackgroundColour.asRgba().equals("rgba(255, 105, 180, 1)"))
assert(loginButtonBackgroundColour.asRgb().equals("rgb(255, 105, 180)"))
颜色不再是问题.
4 - 线程守卫
此类仅在Java中可用
ThreadGuard检查是否仅从创建驱动程序的同一线程中调用了驱动程序.
线程问题 (尤其是在Parallel中运行测试时)
可能遇到神秘并且难以诊断错误.
使用此包装器可以防止此类错误,
并且在发生此类情况时会抛出异常.
以下的示例模拟一种线程冲突的情况:
public class DriverClash {
//thread main (id 1) created this driver
private WebDriver protectedDriver = ThreadGuard.protect(new ChromeDriver());
static {
System.setProperty("webdriver.chrome.driver", "<Set path to your Chromedriver>");
}
//Thread-1 (id 24) is calling the same driver causing the clash to happen
Runnable r1 = () -> {protectedDriver.get("https://selenium.dev");};
Thread thr1 = new Thread(r1);
void runThreads(){
thr1.start();
}
public static void main(String[] args) {
new DriverClash().runThreads();
}
}
结果如下所示:
Exception in thread "Thread-1" org.openqa.selenium.WebDriverException:
Thread safety error; this instance of WebDriver was constructed
on thread main (id 1)and is being accessed by thread Thread-1 (id 24)
This is not permitted and *will* cause undefined behaviour
正如示例所示:
protectedDriver
将在主线程中创建- 我们使用Java的
Runnable
启动一个新进程, 并使用一个新的Thread
运行该进程 - 这两个
Thread
都会发生冲突, 因为主线程的内存中没有protectedDriver
ThreadGuard.protect
会抛出异常
注意:
这不能代替并发运行时使用 ThreadLocal
管理驱动程序的需求.
5 - 使用选择列表元素
Select对象现在将为您提供一系列命令,
用于允许您与 <select>
元素进行交互.
如果您使用的是 Java 或 .NET, 请确保您在代码中已正确加载所需的包. 您可以通过GitHub查看下面示例的完整代码.
请注意,此类仅适用于 HTML 元素 select
和 option
.
这个类将不适用于那些通过 div
或 li
并使用JavaScript遮罩层设计的下拉列表.
类型
选择方法的行为可能会有所不同,
具体取决于正在使用的 <select>
元素的类型.
单选
这是标准的下拉对象,其只能选定一个选项.
<select name="selectomatic">
<option selected="selected" id="non_multi_option" value="one">One</option>
<option value="two">Two</option>
<option value="four">Four</option>
<option value="still learning how to count, apparently">Still learning how to count, apparently</option>
</select>
复选
此选择列表允许同时选定和取消选择多个选项.
这仅适用于具有 multiple
属性的 <select>
元素.
<select name="multi" id="multi" multiple="multiple">
<option selected="selected" value="eggs">Eggs</option>
<option value="ham">Ham</option>
<option selected="selected" value="sausages">Sausages</option>
<option value="onion gravy">Onion gravy</option>
</select>
构建类
首先定位一个 <select>
元素,
然后借助其初始化一个Select
对象.
请注意, 从 Selenium 4.5 开始,
您无法针对禁用的 <select>
元素构建 Select
对象.
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
it('Select an option', async function () {
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
选项列表
共有两种列表可以被获取:
全部选项
获取 <select>
元素中所有选项列表:
List<WebElement> optionList = select.getOptions();
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
option_list = select.options
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
IList<IWebElement> optionList = select.Options;
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
option_list = select.options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
val optionList = select.getOptions()
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
选中的选项
获取 <select>
元素中所选中的选项列表.
对于标准选择列表这将只是一个包含一个元素的列表,
对于复选列表则表示包含的零个或多个元素.
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
selected_option_list = select.all_selected_options
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
selected_option_list = select.selected_options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
}
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
val selectedOptionList = select.getAllSelectedOptions()
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
选项
Select类提供了三种选择选项的方法. 请注意, 对于复选类型的选择列, 对于要选择的每个元素可以重复使用这些方法.
文本
根据其可见文本选择选项
select.selectByVisibleText("Four");
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
select.select_by_visible_text('Four')
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
select.SelectByText("Four");
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
select.select_by(:text, 'Four')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
select.selectByVisibleText("Four")
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
值
根据其值属性选择选项
select.selectByValue("two");
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
select.select_by_value('two')
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
select.SelectByValue("two");
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
select.select_by(:value, 'two')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
assert.equal(true, await fourElement.isSelected())
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
select.selectByValue("two")
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
序号
根据其在列表中的位置选择选项
select.selectByIndex(3);
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
select.select_by_index(3)
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
select.SelectByIndex(3);
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
select.select_by(:index, 3)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
assert.equal(true, await twoElement.isSelected())
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
select.selectByIndex(3)
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
禁用的选项
具有 disabled
属性的选项可能无法被选择.
<select name="single_disabled">
<option id="sinlge_disabled_1" value="enabled">Enabled</option>
<option id="sinlge_disabled_2" value="disabled" disabled="disabled">Disabled</option>
</select>
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}
取消选择选项
只有复选类型的选择列表才能取消选择选项. 您可以对要选择的每个元素重复使用这些方法.
select.deselectByValue("eggs");
Show full example
package dev.selenium.support;
import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.ArrayList;
import java.util.List;
public class SelectListTest extends BaseChromeTest {
@BeforeEach
public void navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
}
@Test
public void selectOption() {
WebElement selectElement = driver.findElement(By.name("selectomatic"));
Select select = new Select(selectElement);
WebElement twoElement = driver.findElement(By.cssSelector("option[value=two]"));
WebElement fourElement = driver.findElement(By.cssSelector("option[value=four]"));
WebElement countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"));
select.selectByVisibleText("Four");
Assertions.assertTrue(fourElement.isSelected());
select.selectByValue("two");
Assertions.assertTrue(twoElement.isSelected());
select.selectByIndex(3);
Assertions.assertTrue(countElement.isSelected());
}
@Test
public void selectMultipleOption() {
WebElement selectElement = driver.findElement(By.name("multi"));
Select select = new Select(selectElement);
WebElement hamElement = driver.findElement(By.cssSelector("option[value=ham]"));
WebElement gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"));
WebElement eggElement = driver.findElement(By.cssSelector("option[value=eggs]"));
WebElement sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"));
List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
List<WebElement> optionList = select.getOptions();
Assertions.assertEquals(optionElements, optionList);
List<WebElement> selectedOptionList = select.getAllSelectedOptions();
List<WebElement> expectedSelection = new ArrayList<WebElement>() {{
add(eggElement);
add(sausageElement);
}};
Assertions.assertEquals(expectedSelection, selectedOptionList);
select.selectByValue("ham");
select.selectByValue("onion gravy");
Assertions.assertTrue(hamElement.isSelected());
Assertions.assertTrue(gravyElement.isSelected());
select.deselectByValue("eggs");
select.deselectByValue("sausages");
Assertions.assertFalse(eggElement.isSelected());
Assertions.assertFalse(sausageElement.isSelected());
}
@Test
public void disabledOption() {
WebElement selectElement = driver.findElement(By.name("single_disabled"));
Select select = new Select(selectElement);
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
select.selectByValue("disabled");
});
}
}
select.deselect_by_value('eggs')
Show full example
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
def test_select_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'selectomatic')
select = Select(select_element)
two_element = driver.find_element(By.CSS_SELECTOR, 'option[value=two]')
four_element = driver.find_element(By.CSS_SELECTOR, 'option[value=four]')
count_element = driver.find_element(By.CSS_SELECTOR, "option[value='still learning how to count, apparently']")
select.select_by_visible_text('Four')
assert four_element.is_selected()
select.select_by_value('two')
assert two_element.is_selected()
select.select_by_index(3)
assert count_element.is_selected()
def test_select_multiple_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'multi')
select = Select(select_element)
ham_element = driver.find_element(By.CSS_SELECTOR, 'option[value=ham]')
gravy_element = driver.find_element(By.CSS_SELECTOR, "option[value='onion gravy']")
egg_element = driver.find_element(By.CSS_SELECTOR, 'option[value=eggs]')
sausage_element = driver.find_element(By.CSS_SELECTOR, "option[value='sausages']")
option_elements = select_element.find_elements(By.TAG_NAME, 'option')
option_list = select.options
assert option_elements == option_list
selected_option_list = select.all_selected_options
expected_selection = [egg_element, sausage_element]
assert selected_option_list == expected_selection
select.select_by_value('ham')
select.select_by_value('onion gravy')
assert ham_element.is_selected()
assert gravy_element.is_selected()
select.deselect_by_value('eggs')
select.deselect_by_value('sausages')
assert not egg_element.is_selected()
assert not sausage_element.is_selected()
def test_disabled_options(driver):
driver.get('https://selenium.dev/selenium/web/formPage.html')
select_element = driver.find_element(By.NAME, 'single_disabled')
select = Select(select_element)
with pytest.raises(NotImplementedError):
select.select_by_value('disabled')
select.DeselectByValue("eggs");
Show full example
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace SeleniumDocs.Support
{
[TestClass]
public class SelectListTest : BaseChromeTest
{
[TestInitialize]
public void Navigate()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
}
[TestMethod]
public void SelectOption()
{
var selectElement = driver.FindElement(By.Name("selectomatic"));
var select = new SelectElement(selectElement);
var twoElement = driver.FindElement(By.CssSelector("option[value=two]"));
var fourElement = driver.FindElement(By.CssSelector("option[value=four]"));
var countElement = driver.FindElement(By.CssSelector("option[value='still learning how to count, apparently']"));
select.SelectByText("Four");
Assert.IsTrue(fourElement.Selected);
select.SelectByValue("two");
Assert.IsTrue(twoElement.Selected);
select.SelectByIndex(3);
Assert.IsTrue(countElement.Selected);
}
[TestMethod]
public void SelectMultipleOption()
{
var selectElement = driver.FindElement(By.Name("multi"));
var select = new SelectElement(selectElement);
var hamElement = driver.FindElement(By.CssSelector("option[value=ham]"));
var gravyElement = driver.FindElement(By.CssSelector("option[value='onion gravy']"));
var eggElement = driver.FindElement(By.CssSelector("option[value=eggs]"));
var sausageElement = driver.FindElement(By.CssSelector("option[value='sausages']"));
IList<IWebElement> optionList = select.Options;
IWebElement[] optionElements = selectElement.FindElements(By.TagName("option")).ToArray();
CollectionAssert.AreEqual(optionElements, optionList.ToArray());
IList<IWebElement> selectedOptionList = select.AllSelectedOptions;
IWebElement[] expectedSelection = { eggElement, sausageElement };
CollectionAssert.AreEqual(expectedSelection, selectedOptionList.ToArray());
select.SelectByValue("ham");
select.SelectByValue("onion gravy");
Assert.IsTrue(hamElement.Selected);
Assert.IsTrue(gravyElement.Selected);
select.DeselectByValue("eggs");
select.DeselectByValue("sausages");
Assert.IsFalse(eggElement.Selected);
Assert.IsFalse(sausageElement.Selected);
}
[TestMethod]
public void DisabledOption()
{
var selectElement = driver.FindElement(By.Name("single_disabled"));
var select = new SelectElement(selectElement);
Assert.ThrowsException<InvalidOperationException>(() => select.SelectByValue("disabled"));
}
}
}
select.deselect_by(:value, 'eggs')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Select List' do
let(:driver) { start_session }
before do
driver.get('https://www.selenium.dev/selenium/web/formPage.html')
end
it 'select options' do
select_element = driver.find_element(name: 'selectomatic')
select = Selenium::WebDriver::Support::Select.new(select_element)
two_element = driver.find_element(css: 'option[value=two]')
four_element = driver.find_element(css: 'option[value=four]')
count_element = driver.find_element(css: "option[value='still learning how to count, apparently']")
select.select_by(:text, 'Four')
expect(four_element).to be_selected
select.select_by(:value, 'two')
expect(two_element).to be_selected
select.select_by(:index, 3)
expect(count_element).to be_selected
end
it 'select multiple options' do
select_element = driver.find_element(name: 'multi')
select = Selenium::WebDriver::Support::Select.new(select_element)
ham_element = driver.find_element(css: 'option[value=ham]')
gravy_element = driver.find_element(css: "option[value='onion gravy']")
egg_element = driver.find_element(css: 'option[value=eggs]')
sausage_element = driver.find_element(css: "option[value='sausages']")
option_elements = select_element.find_elements(tag_name: 'option')
option_list = select.options
expect(option_elements).to eq option_list
selected_option_list = select.selected_options
expected_selection = [egg_element, sausage_element]
expect(selected_option_list).to eq expected_selection
select.select_by(:value, 'ham')
select.select_by(:value, 'onion gravy')
expect(ham_element).to be_selected
expect(gravy_element).to be_selected
select.deselect_by(:value, 'eggs')
select.deselect_by(:value, 'sausages')
expect(egg_element).not_to be_selected
expect(sausage_element).not_to be_selected
end
it 'disabled options' do
select_element = driver.find_element(name: 'single_disabled')
select = Selenium::WebDriver::Support::Select.new(select_element)
expect {
select.select_by(:value, 'disabled')
}.to raise_exception(Selenium::WebDriver::Error::UnsupportedOperationError)
end
end
assert.equal(true, await gravyElement.isSelected())
Show full example
const {By, Browser, Builder} = require('selenium-webdriver')
const assert = require('assert/strict')
const {Select} = require('selenium-webdriver')
describe('Select Tests', async function () {
let driver
before(async function () {
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
await driver.get('https://www.selenium.dev/selenium/web/formPage.html')
})
after(async () => await driver.quit())
it('Select an option', async function () {
const selectElement = await driver.findElement(By.name('selectomatic'))
const select = new Select(selectElement)
const twoElement = await driver.findElement(By.css('option[value=two]'))
const fourElement = await driver.findElement(By.css('option[value=four]'))
const countElement = await driver.findElement(By.css("option[value='still learning how to count, apparently']"))
await select.selectByVisibleText('Four')
assert.equal(true, await fourElement.isSelected())
await select.selectByValue('two')
assert.equal(true, await twoElement.isSelected())
await select.selectByIndex(3)
assert.equal(true, await countElement.isSelected())
})
it('Select by multiple options', async function () {
const selectElement = await driver.findElement(By.name('multi'))
const select = await new Select(selectElement)
const hamElement = await driver.findElement(By.css('option[value=ham]'))
const gravyElement = await driver.findElement(By.css("option[value='onion gravy']"))
const eggElement = await driver.findElement(By.css('option[value=eggs]'))
const sausageElement = await driver.findElement(By.css("option[value='sausages']"))
const optionElements = await selectElement.findElements(By.css('option'))
const optionList = await select.getOptions()
assert.equal(optionList.length, optionElements.length)
for (const index in optionList) {
assert.equal(await optionList[index].getText(), await optionElements[index].getText())
}
const selectedOptionList = await select.getAllSelectedOptions()
const expectedSelection = [eggElement, sausageElement]
assert.equal(expectedSelection.length, selectedOptionList.length)
for (const index in selectedOptionList) {
assert.equal(await selectedOptionList[index].getText(), await expectedSelection[index].getText())
}
await select.selectByValue('ham')
await select.selectByValue('onion gravy')
assert.equal(true, await hamElement.isSelected())
assert.equal(true, await gravyElement.isSelected())
await select.deselectByValue('eggs')
await select.deselectByValue('sausages')
assert.equal(false, await eggElement.isSelected())
assert.equal(false, await sausageElement.isSelected())
})
it('Try selecting disabled option', async function () {
const selectElement = await driver.findElement(By.name('single_disabled'))
const select = await new Select(selectElement)
await assert.rejects(async () => {
await select.selectByValue("disabled")
}, {
name: 'UnsupportedOperationError',
message: 'You may not select a disabled option'
})
})
})
select.deselectByValue("eggs")
Show full example
package dev.selenium.support
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.Select
class SelectListTest : BaseTest() {
@BeforeEach
fun navigate() {
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
}
@Test
fun selectOption() {
val selectElement = driver.findElement(By.name("selectomatic"))
val select = Select(selectElement)
val twoElement = driver.findElement(By.cssSelector("option[value=two]"))
val fourElement = driver.findElement(By.cssSelector("option[value=four]"))
val countElement = driver.findElement(By.cssSelector("option[value='still learning how to count, apparently']"))
select.selectByVisibleText("Four")
Assertions.assertTrue(fourElement.isSelected())
select.selectByValue("two")
Assertions.assertTrue(twoElement.isSelected())
select.selectByIndex(3)
Assertions.assertTrue(countElement.isSelected())
}
@Test
fun selectMultipleOption() {
val selectElement = driver.findElement(By.name("multi"))
val select = Select(selectElement)
val hamElement = driver.findElement(By.cssSelector("option[value=ham]"))
val gravyElement = driver.findElement(By.cssSelector("option[value='onion gravy']"))
val eggElement = driver.findElement(By.cssSelector("option[value=eggs]"))
val sausageElement = driver.findElement(By.cssSelector("option[value='sausages']"))
val optionElements = selectElement.findElements(By.tagName("option"))
val optionList = select.getOptions()
Assertions.assertEquals(optionElements, optionList)
val selectedOptionList = select.getAllSelectedOptions()
val expectedSelection = ArrayList<WebElement>()
expectedSelection.add(eggElement)
expectedSelection.add(sausageElement)
Assertions.assertEquals(expectedSelection, selectedOptionList)
select.selectByValue("ham")
select.selectByValue("onion gravy")
Assertions.assertTrue(hamElement.isSelected())
Assertions.assertTrue(gravyElement.isSelected())
select.deselectByValue("eggs")
select.deselectByValue("sausages")
Assertions.assertFalse(eggElement.isSelected())
Assertions.assertFalse(sausageElement.isSelected())
}
@Test
fun disabledOption() {
val selectElement = driver.findElement(By.name("single_disabled"))
val select = Select(selectElement)
Assertions.assertThrows(UnsupportedOperationException::class.java) {
select.selectByValue("disabled")
}
}
}