Home > Back-end >  Upload Photos Selenium
Upload Photos Selenium

Time:11-18

I need to upload images using selenium.

I'm trying to use the input (attached image) with the sendkeys command, but with no success.

enter image description here

foto = driver.find_element(By.XPATH, "//input[@accept='image/*,image/heif,image/heic']")
        sleep(5)
        foto.click()
        sleep(5)
        foto.send_keys("C:\image11.jpg")

CodePudding user response:

Uploading file with Selenium is done by sending the uploaded file to a special element. This is not an element you are clicking as a user via GUI to upload elements. The element actually receiving uploaded files normally matching this XPath:
//input[@type='file']
Again, this element is not visible to a user.
Try uploading your file with this code:

find_element(By.XPATH, "//input[@type='file']").send_keys("C:\image11.jpg")

UPD
The code I gave you works.
This is the fully working code - I tried this on my PC with my FB account uploading some document. I've erased the screenshot details for privacy reasons, but it clearly worked

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument("--disable-infobars")
options.add_argument("start-maximized")
options.add_argument("--disable-extensions")

# Pass the argument 1 to allow and 2 to block
options.add_experimental_option(
    "prefs", {"profile.default_content_setting_values.notifications": 2}
)

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://www.facebook.com/"
driver.get(url)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='email']"))).send_keys(my_username)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='pass']"))).send_keys(my_password)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='login']"))).click()
driver.get("https://www.facebook.com/marketplace/create/item")
wait.until(EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))).send_keys("C:/Users/my_user/Downloads/doch.jpeg")

This is the screenshot of what this code does: enter image description here

  • Related