Home > Software engineering >  Upload image on Facebook Marketplace with selenium (python)
Upload image on Facebook Marketplace with selenium (python)

Time:11-18

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  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 ?

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']
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