'Handling "select from computer" button in selenium python (upload file)

I'm trying to create an Instagram bot to post something, I am using the Selenium webdriver to achieve this. After click on 'New Post', I want to choose an image from my computer, however I don't know how to do this with the bot.

image

I try to find the 'Select From Computer' button and use send_keys, but this does not work.

def Post(self,items):
    self.driver.find_element_by_css_selector('svg[aria     label="New Post"]').click()
    select_file=self.driver.find_element_by_css_selector('body > div.RnEpo.gpWnf.Yx5HN > div.pbNvD > div > div > div > div.uYzeu > div._C8iK > div > div.qF0y9.Igw0E.rBNOH.YBx95._4EzTm.T9mq-.nGS-Y > div.qF0y9.Igw0E.rBNOH.eGOV_.ybXk5._4EzTm.kEKum > div > button')
    select_file.send_keys('D:\project\python\digikala\images\download.jpg')

    # path="D:\\\\project\\\\python\\\\digikala\\\\images\\\\download.jpg"
    # script = "document.querySelector('body > div.RnEpo.gpWnf.Yx5HN > div.pbNvD > div > div > div > div.uYzeu > div._C8iK > div > div.qF0y9.Igw0E.rBNOH.YBx95._4EzTm.T9mq-.nGS-Y > div.qF0y9.Igw0E.rBNOH.eGOV_.ybXk5._4EzTm.kEKum > div > button').value='" + path + "';"
    #self.driver.execute_script(script)

    for item in items:
        pass


Solution 1:[1]

You do not have to click on upload button and the select a file from your computer. Instead, You can directly do .send_keys like this :

def Post(self,items):
   time.sleep(2)
   select_file = self.driver.find_element_by_css_selector("input[type='file']")
   select_file.send_keys("D:\\project\\python\\digikala\\images\\download.jpg")

Solution 2:[2]

I had the same problem using find_elements_by_css_selector. But it works with find_elements_by_xpath, like this:

select_file = self.driver.find_elements_by_xpath('/html/body/div[8]/div[2]/div/div/div/div[2]/div[1]/form/input')
select_file[0].send_keys("D:\\\\project\\\\python\\\\digikala\\\\images\\\\download.jpg")

In this case, select_file returns a list, so you need to use select_file[0].send_keys('image path') to send your image.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cruisepandey
Solution 2