Lokesh J
Lokesh J

Reputation: 25

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

<button id="upload-button" class="btn btn-default ml-2 ng-pristine ng-valid ng-not-empty ng-
touched" 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.

Upvotes: 1

Views: 2904

Answers (1)

Prophet
Prophet

Reputation: 33361

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)

Upvotes: 3

Related Questions