How to Bypass Selenium Drag & Drop Bug in Python

How to perform drag & drop in Selenium on Python if it doesn’t work

Dmitrii Bormotov
Python Pandemonium
2 min readJan 24, 2021

--

Photo by Markus Spiske on Unsplash

Introduction

Ahoy, mate!

It is a known bug for about a decade that in some cases drag & drop doesn’t work in Selenium — it clicks and holds draggable element and doesn’t release it. I’ve searched through StackOverflow and found a suggestion to use JavaScript, but no code was provided. Hours later I found a code that I can adopt to use in Selenium + Python (but the same approach may be used on Java as well, since it’s a simple JavaScript injection).

Source JavaScript code that performs drag & drop (thanks to druska for sharing it with community):

According to this bug report to webdriver repo, we can say that it’s not actually a Selenium bug, but Selenium users do suffer from it. It’s about a year has passed already and no actions were taken to solve this issue, so I guess it worth to solve it on project side at this moment.

Solving an issue

First what we need to do is modify the script that I’ve mentioned above. We simply have to add this line below of original script and save it (let’s say, as script.js file):

simulateDragDrop(arguments[0], arguments[1]);

You may take this page for further testing according this bug.

So, let’s simply open this page using Selenium and find both draggable (source variable) and droppable (target variable) elements:

browser.get("http://the-internet.herokuapp.com/drag_and_drop")
source = browser.find_element_by_css_selector("#column-a")
target = browser.find_element_by_css_selector("#column-b")

ATTENTION: you must use CSS selectors for draggable and droppable elements in order for this script to work. It’s related to the way that browser search elements in DOM tree using embedded scripts.

Then, let’s read all lines from our script.js file that contains our brand new drag & drop script and save it into javascript variable:

f = open("script.js",  "r")
javascript = f.read()
f.close()

We’re good to go now, let’s simply execute our JavaScript on the opened page:

browser.execute_script(javascript, source, target)

What we do here is simply running script from script.js file and providing it one element to drag and one element to drop.

You may find an example repo with code above here.

Thanks for reading, I hope it helped you to solve this issue or you’ve just learned something new!

--

--