Webdriver: File Upload

后端 未结 7 1095
日久生厌
日久生厌 2020-11-27 18:16

Is there a way to interact with a File Upload box in webdriver? The form field where the path gets put in is read only so I can\'t write to that.

7条回答
  •  有刺的猬
    2020-11-27 18:50

    The problem I found is the upload dialog hangs the webdriver until closed. That is, the element.click which invokes the upload dialog does not return until that upload dialog is closed. To be clear, upload dialog means an OS-native file selection.

    Here is my solution (it's a bit complicated but *shrug* most workarounds for selenium webdriver problems must get complicated).

    # presumes webdriver has loaded the web page of interest
    element_input = webdriver.find_element_by_css_selector('input[id="uploadfile"]')
    handle_dialog(element_input, "foobar.txt")
    
    def handle_dialog(element_initiating_dialog, dialog_text_input):
        def _handle_dialog(_element_initiating_dialog):
            _element_initiating_dialog.click() # thread hangs here until upload dialog closes
        t = threading.Thread(target=_handle_dialog, args=[element_initiating_dialog] )
        t.start()
        time.sleep(1) # poor thread synchronization, but good enough
    
        upload_dialog = webdriver.switch_to_active_element()
        upload_dialog.send_keys(dialog_text_input)
        upload_dialog.send_keys(selenium.webdriver.common.keys.Keys.ENTER) # the ENTER key closes the upload dialog, other thread exits
    


    Using python 2.7, webdriver 2.25.0, on Ubuntu 12, with firefox.

提交回复
热议问题