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

使用Selenium和Python操作下拉菜单选择自定义值或修改选项值

Selenium操作该下拉菜单的两种实现方案

方案1:直接跳转自定义页码(推荐,无需修改option属性)

不需要改动现有下拉选项,直接通过JS给select元素赋值并触发跳转即可,代码如下:

# 你想要跳转的目标页码
target_page = 30
# 直接给下拉菜单设置自定义value
driver.execute_script("arguments[0].value = arguments[1];", b, target_page)
# 触发下拉菜单的change事件,执行跳转逻辑
driver.execute_script("arguments[0].dispatchEvent(new Event('change'));", b)

方案2:修改指定option的value属性

如果需要修改现有option的value值(例如把显示为2的option的value改为30),执行以下代码:

driver.execute_script("""
const selectEle = arguments[0];
// 找到显示文本为2的option选项
const targetOption = Array.from(selectEle.options).find(opt => opt.textContent.trim() === '2');
if (targetOption) {
    targetOption.value = '30';
}
""", b)
# 修改完成后,选中显示为2的选项就会跳转到第30页,可通过Select类选中
from selenium.webdriver.support.ui import Select
select = Select(b)
select.select_by_visible_text("2")

补充:选择现有1-11的页码

如果只需选择下拉菜单已有的1-11的选项,直接用Selenium内置的Select类即可:

from selenium.webdriver.support.ui import Select
select = Select(b)
# 以下三种方式任选其一即可
select.select_by_value("7") # 按value值选择,示例选value=7的选项
select.select_by_index(6) # 按索引选择,索引从0开始计数,示例选第7个选项
select.select_by_visible_text("7") # 按页面显示的文本选择,示例选显示为7的选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 20:30:02