Home > Software engineering >  How to upload file using selenium python in Headless browser for HTML element [type=button]
How to upload file using selenium python in Headless browser for HTML element [type=button]

Time:02-07

<button id="upload-button"  type="button" ng-model="files" ngf-select="uploadFiles($files)" ngf-pattern="pattern" 
accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,application/xml,application/x-zip-compressed" 
multiple="multiple" ngf-keep="true" ngf-valid-only="false" ngf-validate-fn="validate($file, 
invalidFiles)" ngf-model-invalid="invalidFiles" aria-invalid="false" style="">Select file(s)... </button>

This is the HTML code to upload files. When I click this button it is opening a windows filedalogue to upload files.

I tried send_keys() method but it is not working for this type=button

button = self.browser.find_element_by_id('upload-button')
button.send_keys(filepath)

So I tried python library pyautogui to handle the filedialogue but it is not working in Headless browser. Anyone can help me out of this problem using python selenium , it should work in headless browser.

CodePudding user response:

Uploading a file with Selenium is NOT done by sending the file to a button user clicks to open upload dialog etc.
There is a special invisible element on the page that is actually accepting the uploaded file.
This element can be located by this XPath: //input[@type='file'].
So uploading file with Selenium is done by:

button = self.browser.find_element_by_xpath("//input[@type='file']")
button.send_keys(filepath)
  •  Tags:  
  • Related