我希望我的WebDriver脚本在网页触发特定事件后执行一些测试.这可能吗?
在WebDriver脚本中会有某种事件监听器:
document.addEventListener("hello",function(){
console.log("doing tests");
});
这将在网页执行时运行:
var ev = new Event("hello");
document.dispatchEvent(ev);
这是否可能反过来,所以我可以从WebDriver向网页发起一个事件?
最佳答案
是的,可以听一个事件.
此示例侦听文件输入上的“change”事件:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://fiddle.jshell.net/lovlka/N4Jxk/show/")
driver.switch_to_frame(0)
driver.set_script_timeout(30)
# find the input
input_elem = driver.find_element_by_css_selector("#uploadFile")
# add an event listener on an element
driver.execute_script("""\
arguments[0].addEventListener("change",function onchange() {
this.removeEventListener("change",onchange);
window.__file__ = true;
});
window.__file__ = false;
""",input_elem)
# upload the file
input_elem.send_keys(r"C:\text.txt")
# waits for the file
driver.execute_async_script("""\
var callback = arguments[0];
(function fn(){
if(window.__file__)
return callback();
setTimeout(fn,60);
})();
""")
也可以生成一个事件.
此示例模拟HTML5文本删除:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://html5demos.com/drag-anything")
drop_element = driver.find_element_by_id("drop")
drop_format = "text/message"
drop_text = "my text"
driver.execute_script("""\
var tgt = arguments[0],format = arguments[1],data = arguments[2],dataTransfer = {
dropEffect: '',effectAllowed: 'all',files: [ ],items: { format: data },types: [ format ],getData: function (format) { return data; },clearData: function (format) { }
};
var emit = function (event,target) {
var evt = document.createEvent('Event');
evt.initEvent(event,true,false);
evt.dataTransfer = dataTransfer;
target.dispatchEvent(evt);
};
emit('dragenter',tgt);
emit('dragover',tgt);
emit('drop',tgt);
""",drop_element,drop_format,drop_text)