Home > Software design >  How to upload a file (image) with Selenium using python on Linux?
How to upload a file (image) with Selenium using python on Linux?

Time:02-24

I want to automate uploading a file to this website (it's not my website) but this website is created in some js framework (I think it's react). Now I have a problem uploading file, everything I have tried it's not working. I use Linux (distribution Manjaro) and I'm unable to use AutoIT.

This is what I tried.

file_image = 'image.jpg'

#this
uplod_image = browser.find_element_by_xpath('//input[@qa-id="selectFile"]').send_keys(file_image)

#and this
upload_image = browser.find_element_by_class_name("fileUploadBtn_dropzoneElement_38Gmm").send_keys(file_image)

This is inspected code, main problem is that upload is done like div

enter image description here

I usually got this error...

selenium.common.exceptions.ElementNotInteractableException: Message: Element <div > is not reachable by keyboard
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
ElementNotInteractableError@chrome://remote/content/shared/webdriver/Errors.jsm:293:5
webdriverSendKeysToElement@chrome://remote/content/marionette/interaction.js:624:13
interaction.sendKeysToElement@chrome://remote/content/marionette/interaction.js:600:11
sendKeysToElement@chrome://remote/content/marionette/actors/MarionetteCommandsChild.jsm:497:24
receiveMessage@chrome://remote/content/marionette/actors/MarionetteCommandsChild.jsm:151:31

Any idea how to solve this problem?

CodePudding user response:

If you check the input element the style attribute present as display: none; That's the reason it is not interacting even using the valid locator.

You need the change the style of the element to display: block; and then try to upload the file using send_keys()

Use java script executor to change the style.

fileupload=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div[qa-id='dropZone']>input[type='file']")))
driver.execute_script("arguments[0].style.display = 'block';",fileupload)
fileupload.send_keys(path/to/file)

Hope this code will works for you.

You need to import following libraries.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

CodePudding user response:

Normally uploading a file with Selenium is done by:

browser.find_element_by_xpath('//input[@type="file"]').send_keys(file_location)

where file_location is actual absolute path to the file on your local PC.
Like C:/path_to_file/image.jpg

  • Related