Search code examples
pythonselenium-webdriverinstagram

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

  • 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")