1

I am trying to upload a pdf file, but it throws an exception:

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot focus element

Below is the code:

public class FileUploadPopUp {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G://ChromeDriver//chromedriver.exe");

        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("https://pdf2doc.com/");

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.findElement(By.id("pick-files")).sendKeys("F:\\Selenium Complete Notes.pdf"); 
    }

}

This is to automate the file upload action.I want to upload a pdf file. Can anyone please help me in resolving this?

2 Answers 2

2

To upload file you have to use input element with file type, but your pick-files selector is a div, that's why you got an error. Use input[type=file] css selector:

public class FileUploadPopUp {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "G://ChromeDriver//chromedriver.exe");

        WebDriver driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().window().maximize();

        driver.get("https://pdf2doc.com/");

        driver.findElement(By.cssSelector("input[type=file]")).sendKeys("F:\\Selenium Complete Notes.pdf"); 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much.I have a doubt..In this case we have to select div which has wrapper in id?
input[type=file]..can this be used even if the html tag doesn't contain type attribute?
To upload file using Selenium you have to use input with file type
0

if file input is not editable - you can try to change value attribute with JS:

((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', 'F:\\Selenium Complete Notes.pdf');", element);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.