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

如何用Selenium和C#点击自动补全项?输入后下拉列表未显示

解决Priceline租车页面Selenium输入后下拉列表不显示的问题

手动输入与Selenium输入的差异

手动操作时,浏览器会触发完整的DOM事件链(如focus、input、keyup等),网站的下拉提示逻辑依赖这些事件触发JS渲染列表。而Selenium默认的SendKeys()可能只触发部分事件,导致下拉列表无法正常显示。

具体解决步骤

1. 触发完整输入事件

放弃直接使用SendKeys(),先激活输入框,再通过JS注入触发完整事件链:

// 定位目标输入框
var inputBox = driver.FindElement(By.CssSelector("input[placeholder='City, Airport or Address']"));
// 点击激活输入框
inputBox.Click();
// 通过JS设置值并触发input事件
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].value = 'Los Angeles'; arguments[0].dispatchEvent(new Event('input', { bubbles: true }));", inputBox);
// 可选:额外触发keyup事件适配网站逻辑
js.ExecuteScript("arguments[0].dispatchEvent(new Event('keyup', { bubbles: true }));", inputBox);

2. 配置ChromeDriver模拟真实浏览器

部分网站会检测Selenium自动化特征,需配置选项隐藏标识:

ChromeOptions options = new ChromeOptions();
// 禁用自动化控制检测
options.AddArgument("--disable-blink-features=AutomationControlled");
// 模拟真实用户代理(可选,若网站检测UA则添加)
options.AddArgument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
// 启用最大化窗口、禁用扩展
options.AddArgument("--start-maximized");
options.AddArgument("--disable-extensions");
// 初始化驱动
var driver = new ChromeDriver(options);

3. 显式等待下拉列表加载

输入后需等待列表渲染完成,避免提前操作:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// 等待下拉列表可见(需替换为实际的列表选择器)
var dropdown = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div[class*='location-dropdown-menu']")));
// 选择目标选项
dropdown.FindElement(By.XPath(".//div[contains(text(), 'Los Angeles, CA')]")).Click();

额外排查要点

  • 确认输入框定位准确:部分网站会有嵌套的假输入框,需选中真正接收输入的<input>元素
  • 模拟用户输入节奏:可添加短延迟(如Thread.Sleep(500)),避免被反爬机制判定为自动化工具

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:11:03