Mah*_*avi 12 python html5 selenium drag-and-drop selenium-webdriver
我使用的是Python 2.7和Selenium 2.44.
我想在Selenium WD中自动执行拖放操作,但根据其他相关帖子,Selenium尚不支持HTML5中的操作.有没有办法在Python中模拟拖放?
这是我试过的代码:
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()
Run Code Online (Sandbox Code Playgroud)
它不起作用.
ale*_*cxe 24
是的,Selenium 目前不支持 HTML5"拖放" :
其中的建议的解决方法是模拟HTML5拖放通过JavaScript:
drag_and_drop_helper.jsexecute_script()调用传递元素的元素simulateDragDrop()上的函数来执行脚本sourcetargetdropTarget示例代码:
with open("drag_and_drop_helper.js") as f:
js = f.read()
driver.execute_script(js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")
Run Code Online (Sandbox Code Playgroud)
问题是它不会因为它需要而jQuery "按原样"在你的情况下工作.
现在我们需要弄清楚如何动态加载jQuery.谢天谢地,有一个解决方案.
完整的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
with open("jquery_load_helper.js") as f:
load_jquery_js = f.read()
# load drag and drop helper
with open("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'});")
Run Code Online (Sandbox Code Playgroud)
其中jquery_load_helper.js包括:
/** 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]);
Run Code Online (Sandbox Code Playgroud)
结果之前/之后:
