Selenium file upload leaves file selector window o

2020-03-29 08:01发布

问题:

I'm able to upload a file to a remote server using Selenium, but the file selector dialog sticks around even once the file is uploaded. The Selenium FAQ notes that, "You can't interact with the native OS file browser dialog directly, but we do some magic so that...." Given the use of "magic" here it's not surprising that the behavior I get is a little rough around the edges. But there appear to be workarounds. Taking my cues from this answer I have the following code:

import contextlib, time
from selenium import webdriver
import selenium.webdriver.common.action_chains as action_chains
with contextlib.closing(webdriver.Chrome()) as driver:
    driver.get("http://www.bing.com/images")
    driver.find_element_by_id("sbi_t").click()
    driver.find_element_by_id("sbi_file").click()
    driver.find_element_by_id("sbi_file_upload").send_keys("//Loch Ness Monster.jpg")
    print driver.current_url # Still `http://www.bing.com/images` :(
    file_upload = driver.find_element_by_id("sbi_file_upload")
    action_chains.ActionChains(driver).click(file_upload).perform() # https://stackoverflow.com/a/16864547/2829764

But at the end of this the file upload window is still there. I suspect I need a slightly different workaround since I'm on a Mac. Can anyone help?

回答1:

Don't click upload button at all.

Set the filename via send_keys() and click "Go" (tested and works for me):

element = driver.find_element_by_id("sbi_file_upload")
element.send_keys('/Path/to/file.jpeg')
driver.find_element_by_css_selector('div#sbi_sb_ipt span[name=go]').click()