Absolutely, you can definitely listen to an event.
For instance, in this particular scenario, the code is set up to listen for the "change" event on a file input:
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)
# locate the input element
input_elem = driver.find_element_by_css_selector("#uploadFile")
# attach an event listener to the element
driver.execute_script("""\
arguments[0].addEventListener("change", function onchange() {
this.removeEventListener("change", onchange);
window.__file__ = true;
});
window.__file__ = false;
""", input_elem)
# upload the specified file
input_elem.send_keys(r"C:\text.txt")
# wait for the file to be processed
driver.execute_async_script("""\
var callback = arguments[0];
(function fn(){
if(window.__file__)
return callback();
setTimeout(fn, 60);
})();
""")
Moreover, it's also entirely possible to trigger an event programmatically.
In this example, we are simulating a text drop using HTML5 technology:
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)