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

使用Selenium JavaScript选择React Select下拉框失败,求解决方案

Selenium JavaScript实现React Select下拉框选择的解决方案

失效原因分析

  • 元素定位错误:你提供的DOM结构中下拉输入框的ID为react-select-2-input,但测试代码中使用的是react-select-15-input,定位目标本身不匹配
  • React Select组件的输入框默认宽度仅为2px,直接调用click()、sendKeys()方法大概率无法触发组件的交互事件
  • 未触发下拉框展开逻辑,选项元素未渲染到DOM中,无法选中目标选项

正确实现代码

方案1:模拟真实用户交互(推荐)

const { By, until } = require('selenium-webdriver');

// 1. 点击下拉框的展开箭头,触发选项列表渲染
const dropdownTrigger = await driver.findElement(By.css('.css-tlfecz-indicatorContainer:last-child'));
await dropdownTrigger.click();

// 2. 等待目标选项加载完成,点击选中
const targetOption = await driver.wait(
  until.elementLocated(By.xpath(`//*[contains(text(),'David Messi')]`)),
  3000 // 超时时间可自行调整
);
await targetOption.click();

方案2:输入框输入过滤后选择(适合选项较多的场景)

const { By, until } = require('selenium-webdriver');

// 1. 定位输入框,先点击聚焦再输入内容过滤选项
const selectInput = await driver.findElement(By.id('react-select-2-input'));
await selectInput.click();
await selectInput.sendKeys('David Messi');

// 2. 等待过滤后的选项出现,点击选中
const targetOption = await driver.wait(
  until.elementLocated(By.xpath(`//*[contains(text(),'David Messi')]`)),
  3000
);
await targetOption.click();

方案3:直接修改隐藏域(极端场景备用,不触发组件事件的话慎用)

const { By } = require('selenium-webdriver');

// 直接修改表单绑定的隐藏域value
await driver.executeScript(`
  document.querySelector('input[name="transfer.account"]').value = "你要设置的账户值";
`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:24:03