python - How to simulate HTML5 Drag and Drop in Selenium Webdriver? -
i using python 2.7 , selenium 2.44.
i want automate drag , drop action in selenium wd according other related posts actions in html5 not supported selenium yet. there way simulate drag , drop in python?
here code tried:
driver = webdriver.firefox() driver.get("http://html5demos.com/drag") target = driver.find_element_by_id("one") source = driver.find_element_by_id("bin") actionchains = actionchains(driver) actionchains.drag_and_drop(target, source).perform()
and did not work.
yes, html5 "drag&drop" is not supported selenium:
one of suggested workarounds simulate html5 drag , drop via javascript:
- download
drag_and_drop_helper.js
- execute script via
execute_script()
callingsimulatedragdrop()
function onsource
element passingtarget
elementdroptarget
sample code:
with open("drag_and_drop_helper.js") f: js = f.read() driver.execute_script(js + "$('#one').simulatedragdrop({ droptarget: '#bin'});")
the problem won't work in case "as is" since requires jquery
.
now need figure out how dynamically load jquery. thankfully, there solution.
complete working example in python:
from selenium import webdriver jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js" driver = webdriver.firefox() driver.get("http://html5demos.com/drag") driver.set_script_timeout(30) # load jquery helper open("jquery_load_helper.js") f: load_jquery_js = f.read() # load drag , drop helper open("drag_and_drop_helper.js") 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'});")
where jquery_load_helper.js
contains:
/** dynamically load jquery */ (function(jqueryurl, callback) { if (typeof jqueryurl != 'string') { jqueryurl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; } if (typeof jquery == 'undefined') { var script = document.createelement('script'); var head = document.getelementsbytagname('head')[0]; var done = false; script.onload = script.onreadystatechange = (function() { if (!done && (!this.readystate || this.readystate == 'loaded' || this.readystate == 'complete')) { done = true; script.onload = script.onreadystatechange = null; head.removechild(script); callback(); } }); script.src = jqueryurl; head.appendchild(script); } else { callback(); } })(arguments[0], arguments[arguments.length - 1]);
before/after result:
Comments
Post a Comment