Upload image on Facebook Marketplace with selenium (python)

Question:

I am trying to automatize the creation of ads on facebook marketplace.
I success in log in and go on the correct page.
But I don’t how to upload an image with selenium.
Indeed, the element which handle the uploading of image is not an input type=file but a div which has a role of a button which open the windows file window in order to choose a file.

This is the html of the element :

<div class="x1i10hfl x1qjc9v5 xjbqb8w xjqpnuy xa49m3k xqeqjp1 x2hbi6w x13fuv20 xu3j5b3 x1q0q8m5 x26u7qi x972fbf xcfux6l x1qhh985 xm0m39n x9f619 x1ypdohk xdl72j9 x2lah0s xe8uvvx xdj266r x11i5rnm xat24cr x1mh8g0r x2lwn1j xeuugli xexx8yu x4uap5 x18d9i69 xkhd6sd x1n2onr6 x16tdsg8 x1hl2dhg xggy1nq x1ja2u2z x1t137rt x1o1ewxj x3x9cwd x1e5q0jg x13rtm0m x1q0g3np x87ps6o x1lku1pv x1a2a7pz x78zum5 x1iyjqo2" role="button" tabindex="0">

I already tried this code :

driver.find_element(By.XPATH, element_xpath).send_keys(absolute_path)

But it doesn’t work

Is there someone who already tried and succeeded in ?

Asked By: Joe Debray

||

Answers:

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']
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:webdriverschromedriver.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

Answered By: Prophet