You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在pytest中如何获取下拉菜单默认选中值并验证默认选项

验证下拉菜单默认选中项的pytest测试方案

针对你提供的HTML结构,这里有两种可靠的方法来验证Option B是默认选中项,结合网页自动化工具和pytest实现:

方法1:通过Selenium Select类获取默认选中项

利用Selenium提供的Select类,可以直接获取下拉菜单中当前选中的选项,代码示例如下:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import pytest

def test_default_selected_option():
    # 初始化Chrome浏览器驱动(需确保chromedriver已配置到环境)
    driver = webdriver.Chrome()
    driver.get("你的目标网页URL")
    
    # 定位下拉菜单元素
    select_element = driver.find_element("id", "id")
    # 初始化Select操作对象
    select = Select(select_element)
    
    # 获取默认选中的选项
    selected_option = select.first_selected_option
    
    # 验证选项的value和文本是否符合预期
    assert selected_option.get_attribute("value") == "optionB"
    assert selected_option.text == "Option B"
    
    driver.quit()

方法2:直接检查目标Option的selected属性

直接定位Option B对应的元素,检查它的selected属性状态,适合仅验证默认初始状态的场景:

from selenium import webdriver
import pytest

def test_option_b_selected_by_default():
    driver = webdriver.Chrome()
    driver.get("你的目标网页URL")
    
    # 通过CSS选择器定位Option B元素
    option_b = driver.find_element("css selector", "#id option[value='optionB']")
    
    # 断言该选项处于选中状态
    assert option_b.is_selected()
    
    driver.quit()

静态HTML场景的替代方案

如果测试的是无需动态加载的静态页面,也可以用BeautifulSoup直接解析验证,无需启动浏览器:

from bs4 import BeautifulSoup
import requests
import pytest

def test_default_selected_option_static():
    response = requests.get("你的目标网页URL")
    soup = BeautifulSoup(response.text, "html.parser")
    
    # 定位下拉菜单标签
    select_tag = soup.find("select", id="id")
    # 找到带有selected属性的选项
    selected_option = select_tag.find("option", selected=True)
    
    assert selected_option["value"] == "optionB"
    assert selected_option.text == "Option B"

内容的提问来源于stack exchange,提问作者Kartoffel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:40:36