Using Selenium and Python, the goal is to drag and drop an element to a target, as shown with this HTML5 test website. Selenium should be able to do that too with a simple call to an ActionChains(driver) method, as shown here in section 3.3: . However, to my dismay it appears that the functionality is not implemented for HTML5 based websites, as explained in a selenium bug report.
Ok, time for a solution, and someone appears to have found a nice workaround.
Problem is an error that does not make sense. Here is my implementation:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# drag and drop not working with ActionChains and HTML5
from selenium.webdriver import ActionChains
class PythonDragAndDrop(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search(self):
driver = self.driver
driver.get("http://html5demos.com/drag")
self.assertIn("HTML5 Demo: Drag and drop", driver.title)
# workaround
jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js"
driver.set_script_timeout(30)
# load jquery helper
with open("/Users/me/Desktop/dragNDrop/jquery_load_helper.js") as f:
load_jquery_js = f.read()
# load drag and drop helper
with open("/Users/me/Desktop/dragNDrop/drag_and_drop_helper.js") as f:
drag_and_drop_js = f.read()
# load jquery
driver.execute_async_script(load_jquery_js, jquery_url)
# perform drag&drop
driver.execute_script(drag_and_drop_js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")
def tearDown(self):
self.driver.close() # closes one browser tab
# driver.quit() # closes browser and all tabs
if __name__ == "__main__":
unittest.main()
The result is an error:
Traceback (most recent call last):
File "testDragAndDrop.py", line 35, in test_search
driver.execute_async_script(load_jquery_js, jquery_url)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 418, in execute_async_script
{'script': script, 'args':converted_args})['value']
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium-2.45.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: illegal character
Stacktrace:
at handleEvaluateEvent (http://html5demos.com/drag:69)
What is most likely causing this error, and how might I fix it?
Note: Using Python in Xcode to test Drag and Drop functionality in Firefox.