pythonselenium-webdriverinstagram

"Something went wrong" when trying to send image to input


I am trying to make a post in Instagram using Selenium and Python. But when I tried to send image to input site only shows an error. How can I fix that?

Frame that says "Something went wrong"

imports:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import pickle

Code:

driver.get("https://www.instagram.com/name/")
time.sleep(5)
post = driver.find_element(By.XPATH, "(//div[@class='x1n2onr6'])[9]")
post.click()
time.sleep(5)
file_input = driver.find_element(By.XPATH, "//input[@type='file' and contains(@class,'_ac69')]")
file_path = "C:\py\placeholder.jpg"  
file_input.send_keys(file_path)
time.sleep(5)

I have tried several methods of sending route of image to input: with slash (/), with backslash (\) and with double backslash (\\). I can't find another input for files on site, so I tried all this with only one input.

I expected that I would be able to insert a photo into the input, but the site shows an error.


Solution

  • before trying the code below, make sure the image upload works properly in manual mode

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import time
    
    # Path to the image file
    file_path = r"C:\py\placeholder.jpg"
    
    # Initialize the WebDriver
    driver = webdriver.Chrome()
    
    try:
        driver.get("https://www.instagram.com/")
        time.sleep(5)
    
        # Assuming you're already logged in
        # Locate and click the "Create Post" button
        post_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "(//div[@class='x1n2onr6'])[9]"))
        )
        post_button.click()
    
        # Wait for the file input to appear
        file_input = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))
        )
    
        # Send the file path to the input
        file_input.send_keys(file_path)
    
        time.sleep(5)  # Wait for the upload to process
    finally:
        driver.quit()