C# Selenium点击file输入元素触发WebDriverArgumentException报错
问题描述
编写HTML页面Selenium测试用例时,使用C#代码点击type="file"的输入元素抛出异常,手动点击该元素正常,其他元素操作无问题,已将相关组件更新至最新版本。
异常信息
Exception User-Unhandled:
OpenQA.Selenium.WebDriverArgumentException:'invalid argument (Session info: chrome=131.0.6778.205)'
涉及代码
C# 测试代码
using OpenQA.Selenium; IWebElement element = driver.FindElement(By.XPath(pathString)); element.Click();
对应HTML元素
<div class="col-md-12" style="margin:10px;"> <input class="form-control" type="file" id="fileToUpload" name="file" /> <span class="field-validation-error text-danger" id="spanfile"></span> </div>
版本信息
- Assembly WebDriver, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null
- Selenium.WebDriver : 4.27.00
- Selenium.WebDriver.ChromeDriver : 131.0.6778.20400
- Chrome版本 131.0.6778.205(官方版本)(64位)
解决方法
优先使用SendKeys上传文件
对于file类型输入框,Selenium官方推荐直接通过SendKeys传入文件绝对路径完成上传,无需模拟点击触发系统文件选择框,这是更稳定且符合规范的方式:IWebElement fileInput = driver.FindElement(By.Id("fileToUpload")); // 替换为实际的文件绝对路径 fileInput.SendKeys(@"D:\test_files\sample.pdf");使用JavaScript强制点击(若必须模拟点击)
若业务场景需要模拟点击操作,可通过JavaScript执行点击绕过元素交互限制:IWebElement fileInput = driver.FindElement(By.Id("fileToUpload")); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", fileInput);等待元素完全可交互
确保元素处于可交互状态后再操作,添加显式等待:var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement fileInput = wait.Until(d => d.FindElement(By.Id("fileToUpload")).Displayed && d.FindElement(By.Id("fileToUpload")).Enabled); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", fileInput);确认ChromeDriver与Chrome版本完全匹配
当前ChromeDriver版本(131.0.6778.204)与Chrome版本(131.0.6778.205)存在微小构建号差异,可尝试下载与Chrome版本完全一致的ChromeDriver重新测试。
内容的提问来源于stack exchange,提问作者TS-
相关产品推荐
相关产品推荐

