2

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 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

That did it, thanks! I had to comment out the last line to avoid selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document but the code is working fine without it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.