Search code examples
pythonseleniumselenium-webdriverweb-scrapinginstagram

Give upload file path to Instagram with Selenium and python


I'm testing some web scraping on Instagram with Selenium and Python.

In this case I want to upload a picture.

Normally you have to click on the upload icon and choose the file from a window. How can I manage it with Selenium?

I tried:

driver.find_element_by_class_name("coreSpriteFeedCreation").send_keys('C:\\path-to-file\\file.jpg')

and also with find_element_by_xpath but I get an exception:

selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element

I tried also only with click() but nothing happens.

Any Idea?

EDIT
Thanks to @homersimpson comment I tried this:

actions = ActionChains(driver)
element = driver.find_element_by_class_name("coreSpriteFeedCreation")
actions.move_to_element(element)
actions.click()
actions.send_keys('C:\\path-to-file\\file.jpg')
actions.perform()

Now the window to choose the file appears. The problem is that I would like to avoid this window and give directly the path of my file.


Solution

  • If right understand, you are trying to avoid handling with a native window. You can try this:

    # get all inputs
    inputs = driver.find_elements_by_xpath("//input[@accept = 'image/jpeg']").send_keys(os.getcwd() + "/image.png")
    

    Now you can try all of them. I don't know which of them will work.

    More about os.getcwd() is here

    To be able to perform this code you have to have an element like this:

    <input type="file" name="fileToUpload" id="fileToUpload2" class="fileToUpload">
    

    EDIT:

    It looks like instagram turned of input fields interaction for posts. For Account image it still works, but not for posting. I assume it is was done to prevent bots to post images. Anyway, there is a solution for this problem. You can use AutoIt like this:

    import autoit
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys
    
    ActionChains(driver).move_to_element( driver.find_element_by_xpath("//path/to/upload/button")).click().perform()
    handle = "[CLASS:#32770; TITLE:Open]"
    autoit.win_wait(handle, 60)
    autoit.control_set_text(handle, "Edit1", "\\file\\path")
    autoit.control_click(handle, "Button1")