简体   繁体   中英

Selenium file upload leaves file selector window open (OS/X and Python)

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM