我正在使用 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()
但它没有用。
最佳答案
是的,Selenium 目前不支持 HTML5“拖放”:
suggested workarounds 之一是通过 JavaScript 模拟 HTML5 拖放:
- 下载
drag_and_drop_helper.js
- 通过
execute_script()
在传递target
的source
元素上调用simulateDragDrop()
函数来执行脚本元素作为dropTarget
示例代码:
with open("drag_and_drop_helper.js") as f:
js = f.read()
driver.execute_script(js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")
问题是它不会“按原样”在您的情况下工作,因为它需要 jQuery
。
现在我们需要弄清楚如何动态加载 jQuery。谢天谢地,there is a solution .
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'});")
其中 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]);
结果之前/之后:
关于python - 如何在Selenium Webdriver中模拟HTML5拖放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29381233/