如何模拟HTML5在Selenium Webdriver中的拖放?

如何模拟HTML5在Selenium Webdriver中的拖放?

问题描述:

我使用Python 2.7和Selenium 2.44。如何模拟HTML5在Selenium Webdriver中的拖放?

我想自动化拖放硒WD行动,但根据其他相关的职位行动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() 

,并没有奏效。

是,HTML5 “拖&降” 目前不支持硒:

其中suggested workarounds的是模拟HTML5拖放通过JavaScript下降

示例代码source元素上调用simulateDragDrop()函数执行脚本:

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]); 

前/后的结果:

+0

非常感谢@alecxe – Mahmor 2015-04-04 22:29:51

+0

你的例子是仍在工作。我设法翻译它并在C#中使用它。感谢您的帮助! – 2015-08-11 18:29:51

+5

我将此帮手转换为本地JS,无需注入jQuery:https://gist.github.com/druska/624501b7209a74040175 – Druska 2015-08-26 15:01:34