King
King

Reputation: 1

Is there any way to upload file using selenium in headless chrome?

I'm creating a script which requires me to upload a file, so I write something like:

    @FindBy(css = "div[title='Add an attachment'] button")
    private WebElementFacade FILE_UPLOAD_BUTTON;

    Path path = Paths.get(System.getProperty("user.dir"));

    withTimeoutOf(20, TimeUnit.SECONDS).waitFor(ExpectedConditions.visibilityOf(FILE_UPLOAD_BUTTON));
    FILE_UPLOAD_BUTTON.click();

    filePath = Paths.get(path.toString(), "FolderName", "ActualFileName.pdf");

    StringSelection fullPath = new StringSelection(filePath.toString());
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(fullPath, fullPath);

    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    pause(2000);

And it works fine, but NOT when in Headless chrome. Any ideas on how can I do file upload in Headless chrome? TIA.

Edit: Added inquiry to serenity and wakaleo doubted that Robot class will work on headless chrome since it interacts with the real UI. I also tried his suggestion to use Standard Selenium Actions like chord org.openqa.selenium.Keys; and actions org.openqa.selenium.interactions.Actions; and both still didn't work

Upvotes: 0

Views: 9052

Answers (4)

Nikhilkumar Hiragond
Nikhilkumar Hiragond

Reputation: 41

Yes you can use sendkeys for file upload with headless chrome.

  • Key point here to find out appropriate element.
  • sendkeys works perfectly with input tag (file as type in case of file upload).
  • Find out input tag reference if it is wrapped in other tag
  • Check out below example
<p-fileupload id="file_upload_id">
   <div >
      <span>
        <span>Choose file</span>
        <input type="file" accept=".csv">
      </span>
   </div>
</p-fileupload>
  • Find element using xpath
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.WebElement;

@FindBy(xpath="//[@id=\"file_upload_id\"]//following::input[@type=\"file\"]")
@CacheLookup
private WebElement fileupload;
  • setup headless chrome driver
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public  static void initialization() {  
   String browsername=prop.getProperty("browser");
    if(browsername.equals("chrome")) 
    { 
     System.setProperty("webdriver.chrome.driver","...//path-to-chrome-driver//Drivers//chromedriver");
     ChromeOptions chromeOptions = new ChromeOptions();
     chromeOptions.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200","--ignore-certificate-errors","--disable-extensions","--no-sandbox","--disable-dev-shm-usage");
     driver=new ChromeDriver(chromeOptions);
   }

  • Send file using sendkey
String userDir = System.getProperty("user.dir");
String sep = System.getProperty("file.separator");
String path=userDir + sep + "Files_dir_name" + sep + "sample.csv";
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); 
fileupload.sendKeys(value);

Note: userDir - root directory where project runs, file seperator - to resolve file path issue across OS

Upvotes: 0

Ali
Ali

Reputation: 1689

Use the below code to upload file in the headless mode:

    ChromeOptions options = new ChromeOptions();
            options.addArguments("--headless");
            WebDriver driver = new ChromeDriver(options);
            driver.get("http://nervgh.github.io/pages/angular-file-upload/examples/simple/");
            driver.findElement(By.xpath("(//input[@uploader='uploader'])[2]")).sendKeys("C:\\NotBackedUp\\Python\\selenium-2.7.0\\py\\selenium\\selenium.py");
// Then click on some upload button

Give the exact full path of the file that you want to upload in the sendKeys() method.

Upvotes: 1

Timothy T.
Timothy T.

Reputation: 1091

It doesn't work because you're using a Robot class, which isn't ideal for headless execution since the browser isn't visible anyway.

Make sure that your upload element can be visible.

After that you upload with the below:

driver.findElement(By.id("uploadElement")).sendKeys("path/to/file");

Upvotes: 3

akshay patil
akshay patil

Reputation: 688

you can upload file in selenium using AutoIt and it's editor

1.You need to install the Autoit and its script editor

I have shared the link through you can download and use it

https://www.autoitscript.com/site/autoit/downloads/

  1. you need to create autoit file and need to pass the file location and some script like and name the file as you want like i have given File Upload.au3 , .au3 extension comes automatic

    ControlFocus("Open","","Edit1")
    ControlSetText("Open","","Edit1","E:\AutoIT\id.pdf")
    ControlClick("Open","","Button1")
    
  2. you need to right click on file upload.au3 file and compile it then it will create executing file File Upload.exe

  3. then you need to specify in selenium where you need to execute and upload the file like in my project after clicking upload button i am executing this file using Runtime.getRuntime().exec(Globals.PROG_FILEUPLOAD);

where Global.PROG_FILEUPLOAD is path to the File Upload.exe like

PROG_FILEUPLOAD= "E:/AutoIT/File Upload.exe"

I have also shared the link for an reference you can use if you have any doubts

https://www.guru99.com/use-autoit-selenium.html

Upvotes: 0

Related Questions