Home > database >  Image upload with Slenium Python
Image upload with Slenium Python

Time:10-17

How can I upload the image in this line of code.

Detail, I need to click on the field where I'm going to upload the file, I can't use the command SEND_KEYS(file path)

Here's the code I'm using.

An alternative I found was pyautogui, but I didn't like it, because it uses the keyboard to execute the command.

    foto = driver.find_element(By.XPATH, "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[4]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/i[1]").click()
    sleep(5)
    pyautogui.write(r"C:\__Imagens e Planilhas Python\Facebook\Imagens\nome3.png")
    pyautogui.press("enter")

screen that opens to upload the file

enter image description here

CodePudding user response:

Uploading file with Selenium is normally done with the following code:

uploading_element = driver.find_element(By.XPATH, "//input[@type='file']")
uploading_element.send_keys(path_to_the_file_to_be_uploaded)

In you case this should work:

uploading_element = driver.find_element(By.XPATH, "//input[@type='file']")
uploading_element.send_keys("C:\__Imagens e Planilhas Python\Facebook\Imagens\nome3.png")

No need to send Keys.ENTER, no need to use r with path.
Make sure the page is properly loaded when you perform this action.
Possibly you will need to add a wait, so your code can be as following:

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

wait = WebDriverWait(driver, 20)

wait.until(EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))).send_keys("C:\__Imagens e Planilhas Python\Facebook\Imagens\nome3.png")
  • Related