Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python with Selenium: Drag and Drop from file system to webdriver?

I have to automate a web-application, which contains a drag and drop area for uploading files from the local file system. My test environment is developed using Python. For the automation tests I have used Selenium, but it is not possible to drag files from the file system, once the upload area is a div tag (No input tag - this way I know it would be easy).

I read a lot of different articles, but by the moment none worked for me. It's important to highlight that I'm not interested in using AutoIT, only native python with selenium.

I found this Selenium: Drag and Drop from file system to webdriver? what looks really promising, however I do not know to adapt to Python.

Thank you a lot in advance!

like image 280
FelipeG Avatar asked Apr 13 '17 02:04

FelipeG


1 Answers

Here's the python version of the trick with input injection via script.

JS_DROP_FILE = """
    var target = arguments[0],
        offsetX = arguments[1],
        offsetY = arguments[2],
        document = target.ownerDocument || document,
        window = document.defaultView || window;

    var input = document.createElement('INPUT');
    input.type = 'file';
    input.onchange = function () {
      var rect = target.getBoundingClientRect(),
          x = rect.left + (offsetX || (rect.width >> 1)),
          y = rect.top + (offsetY || (rect.height >> 1)),
          dataTransfer = { files: this.files };

      ['dragenter', 'dragover', 'drop'].forEach(function (name) {
        var evt = document.createEvent('MouseEvent');
        evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
        evt.dataTransfer = dataTransfer;
        target.dispatchEvent(evt);
      });

      setTimeout(function () { document.body.removeChild(input); }, 25);
    };
    document.body.appendChild(input);
    return input;
"""

def drag_and_drop_file(drop_target, path):
    driver = drop_target.parent
    file_input = driver.execute_script(JS_DROP_FILE, drop_target, 0, 0)
    file_input.send_keys(path)

As drop_target pass it some element visible on the page.

The approach is to invoke a javascript using selenium's execute_script function to emulate drag and drop events. The code works as following:

  1. selenium invokes javascript code
  2. javascript creates input element and attaches it to DOM
  3. javascript attaches a handler to the input which emulates mouse events that happens when user actually drops a file, namely dragenter, dragover, drop.
  4. selenium updates the input with the path to the file. At this point the handler from step 2 is invoked and it emulates drag and drop events.
like image 123
Roman Konoval Avatar answered Oct 06 '22 02:10

Roman Konoval