无法通过 selenium 中的 sendkeys 上传文件

Unable to File Upload via sendkeys in selenium

我无法使用 selenium 中的 sendkeys 上传文件。甚至我尝试在不同的网站上上传文件。甚至我换了浏览器。早些时候我使用 Chrome 现在我也尝试了 Mozilla。我遇到了一个例外。让我分享下面的脚本

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FileUpload {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        

        System.setProperty("webdriver.chrome.driver","c:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        
        driver.get("https://html.com/input-type-file/");
        
    
        
        driver.findElement(By.xpath("//input[@id='fileupload']")).sendKeys("E:\1.My Task\My Task123");

    }

}


Error ----------------------

Exception in thread "main" org.openqa.selenium.InvalidArgumentException: invalid argument: File not found : E:.My Task\My Task123
  (Session info: chrome=92.0.4515.131)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'LAPTOP-D3V0TN3J', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_291'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 92.0.4515.131, chrome: {chromedriverVersion: 92.0.4515.43 (8c61b7e2989f2..., userDataDir: C:\Users\gunve\AppData\Loca...}, goog:chromeOptions: {debuggerAddress: localhost:54243}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: fe1a2bfd380827509bef42daa3cee01e
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:106)
    at JavaNewLessons.FileUpload.main(FileUpload.java:25)

如果网页中有input标签,属性为type,值为文件,可以直接send_keys

所以,你应该更换

driver.findElement(By.xpath("//input[@id='fileupload']")).sendKeys("E:\1.My Task\My Task123");

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("E:\1.My Task\My Task123");

此外,我建议您在执行此操作之前让 Explicit 等待。

更新 1:

Explicit waits are available to Selenium clients for imperative, procedural languages. They allow your code to halt program execution, or freeze the thread, until the condition you pass it resolves. The condition is called with a certain frequency until the timeout of the wait is elapsed. This means that for as long as the condition returns a falsy value, it will keep trying and waiting.

Since explicit waits allow you to wait for a condition to occur, they make a good fit for synchronising the state between the browser

and its DOM, and your WebDriver script.

代码:

new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@type='file']"))).sendKeys("E:\1.My Task\My Task123");

可以参考这里,看看官方怎么说click here

错误说得很清楚,您使用的是错误的上传文件路径。
E:\1.My Task\My Task123 不是有效的文件路径。
此外,此路径必须包含文件本身。
它不能只是文件夹的路径。
它应该是这样的:

'C:\Users\yourName\picture.png'

通常也可以通过

找到要将文件发送到的元素
//input[@type='file']

XPath,所以你的命令应该是这样的:

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("C:\Users\yourName\picture.png");