开发者问题收集

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

2021-08-11
1920

我无法使用 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:\1.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)

2个回答

如果网页包含任何带有属性 type 且值为 file 的 input 标签,则可以直接执行 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");

另外,我建议您在执行此操作之前进行显式等待。

更新 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");

您可以参考此处,看看官方说了什么 点击此处

cruisepandey
2021-08-11

错误清楚地表明,您使用的要上传的文件路径是错误的。
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");

Prophet
2021-08-11