[selenium] Solution to HTML5 drag and drop with python

Selenium is a great web app automation tool which have several variants, I am using python to implement selenium on this https://the-internet.herokuapp.com/drag_and_drop, Selenium has an ActionChain that can do drag and drop, but this is not working in HTML5, the solution in another language (perhaps is ruby?) can be found here.

I have converted the solution into python for my reference in future should I encounter a HTML5 webapp that has drag and drop functionality.

First of all borrow the javascript from rcorreia in github then save it as a js script file, I followed the solution and save the script as dnd.js. Below is the code to solve the problem. I created two function for file operation, one is to find file i.e. dnd.js and the webdriver, another function is to open the dnd.js.

from selenium import webdriver
import os

def find_file(base="C:\\", name=None):
    for root, dirs, filename in os.walk(base):
        if name in filename:
            return os.path.join(root, name)

def open_file(filepath):
    with open(filepath, "r") as js:
        return js.read()

# Solution from http://elementalselenium.com/tips/39-drag-and-drop
js_path = find_file(name="dnd.js")
js_script1 = open_file(js_path)
js_script2 = """
$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});
driver = webdriver.Firefox(executable_path=find_file(name="geckodriver.exe"))
driver.execute_script(js_script1 + js_script2)
This is the original state in the website.
This is the state after selenium.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s