Selenium / Python - 在 window 中上传文件

Selenium / Python - Upload a file in window

我想将照片上传到 Instagram,但 send_keys() 什么也没做。

username = driver.find_element_by_name('username')
username.send_keys(user[0])
password = driver.find_element_by_name('password')
password.send_keys(user[1])
submit = driver.find_element_by_tag_name('form')
submit.submit()
sleep(5)
driver.get('https://www.instagram.com/')
sleep(7)
elem = driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]').click()
elem = driver.find_element_by_xpath('//*[@id="react-root"]/section/nav[2]/div/div/div[2]/div/div/div[3]')
elem.click()
elem.send_keys("C:\Users\chainsaw\my-awesome-meme.jpeg")
sleep(5)

Window 只是弹出,但没有任何反应。谢谢。

好吧,我昨天刚用自己的代码解决了这个问题。您必须 import pyautogui 因为打开的 window 不是浏览器的一部分。

    image_name = "full path"
    pyautogui.press('f4')
    sleep(4)
    for i in range(0, numberOfchrachtersOfYourUser, 1):
        pyautogui.press('backspace')
        sleep(0.1)
    sleep(7)
    folder_name_parts = image_name.split('/')
    folder_name = ""
    for i in range(0, len(folder_name_parts) - 1, 1):
        if i > 0:
            folder_name += "/"
        folder_name += folder_name_parts[i]
    pyautogui.write(folder_name)
    sleep(5)
    pyautogui.press('enter')
    sleep(0.2)
    pyautogui.press('enter')
    sleep(0.2)
    pyautogui.press('enter')
    sleep(5)
    sh_image_name = image_name.split('/')[len(image_name.split('/')) - 1]
    pyautogui.write(sh_image_name)
    pause(2)
    pyautogui.press('enter')

现在您应该会在浏览器中看到您的图片。 1 进一步提示:如果您想标记其他配置文件,则必须模拟移动设备。在 Chrome 你这样做:

    pyautogui.keyDown('ctrl')
    pyautogui.keyDown('shift')
    pyautogui.press('i')
    pause(1)
    pyautogui.press('m')
    pyautogui.keyUp('ctrl')
    pyautogui.keyUp('shift')