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

Selenium WebDriver:如何在含合并单元格的动态表格中选中下拉框首个选项

问题背景

以下是包含合并单元格(colspan)的动态表格示例:

<table id='table1'>
<tbody>
    <tr>
        <td colspan='2'>Food</td>
    </tr>
    <tr>
        <td>Burger</td>
        <td>
            <select class="form-control input-sm" id="xx2" onchange="count(this)">
                <option value="1">Burger</option>
                <option value="2">spaghetti</option>
                <option value="3">Kebab</option>
            </select>
        </td>
    </tr>       
    <tr>
        <td colspan='2'>Drink</td>
    </tr>
    <tr>
        <td>Burger</td>
        <td>
            <select class="form-control input-sm" id="kj2" onchange="count(this)">
                <option value="1">Coffe</option>
                <option value="2">Tea</option>
                <option value="3">Milk</option>
            </select>
        </td>
    </tr>
    <tr>
        <td colspan='2'> ... </td>
    </tr>
    <tr>
        <td> .......... </td>
        <td>
            <select class="form-control input-sm" id="jj" onchange="count(this)">
                <option value="1"> ... </option>
                <option value="2"> ..... </option>
                <option value="3"> .... </option>
            </select>
        </td>
    </tr>       
</tbody>
</table>

已通过以下Selenium代码获取到表格元素:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="table1"]/tbody')))    
table = driver.find_element(By.XPATH, '//*[@id="table1"]/tbody')

需求:选中该动态表格内所有下拉框的第一个选项。

解决方案

可以通过以下两种方式实现:

方法一:基于已获取的表格元素定位下拉框

从已拿到的表格元素出发,定位所有<select>标签,再借助Selenium的Select类操作下拉框:

from selenium.webdriver.support.ui import Select

# 获取表格内所有下拉框元素
select_elements = table.find_elements(By.TAG_NAME, 'select')

# 遍历每个下拉框,选中第一个选项
for select in select_elements:
    dropdown = Select(select)
    # 通过索引选择第一个选项(索引从0开始)
    dropdown.select_by_index(0)
    # 可选:也可通过value属性或可见文本选择,比如第一个选项value固定为1时
    # dropdown.select_by_value('1')
    # 或通过文本选择
    # dropdown.select_by_visible_text(dropdown.options[0].text)

方法二:显式等待所有下拉框加载完成后操作

如果表格是动态渲染的,为确保所有下拉框都已可交互,可先等待所有<select>元素加载完成:

from selenium.webdriver.support.ui import Select

# 等待表格内所有下拉框加载完成并可交互
select_elements = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.XPATH, '//*[@id="table1"]/tbody//select'))
)

# 遍历选中第一个选项
for select in select_elements:
    Select(select).select_by_index(0)

注意事项

  • 若下拉框由JS动态生成,可将等待条件替换为EC.element_to_be_clickable,确保下拉框可正常交互。
  • 若存在禁用的下拉框,可添加判断跳过:if select.is_enabled(): Select(select).select_by_index(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:23:55