下面将使用WebDriver中的send_keys来模拟键盘按键输入
测试用例场景
send_keys方法可以模拟一些组合键操作:
- ctrl+a
- ctrl+c
- ctrl+v
- 等。
另外有时候我们需要在测试时使用tab键将焦点转移到下一个元素,这时候也需要send_keys。在某些更复杂的情况下,还会出现使用send_keys来模拟上下键来操作下拉列表的情况。
Python脚本
测试HTML代码:
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>send keys</title> <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" /> </head> <body> <h3>send keys</h3> <div class="row-fluid"> <div class="span3"> <div class="well"> <label>A</label> <textarea rows="10", cols="10" id="A">I think watir-webdriver is better than selenium-webdriver</textarea> </div> </div> <div class="span3"> <div class="well"> <label>B</label> <textarea rows="10", cols="10" id="B"></textarea> </div> </div> </div> </body> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> </html>
测试Python代码:
from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep import os if 'HTTP_PROXY' in os.environ: del os.environ['HTTP_PROXY'] dr = webdriver.Firefox() file_path = 'file:///' + os.path.abspath('send_keys.html') dr.get(file_path) #todo: copy the content of A dr.find_element_by_id('A').send_keys((Keys.CONTROL,'a')) sleep(5) dr.find_element_by_id('A').send_keys((Keys.CONTROL,'x')) sleep(5) #todo:paste content of A to B dr.find_element_by_id('B').send_keys((Keys.CONTROL,'v')) sleep(5) #todo:send keys to A dr.find_element_by_id('A').send_keys('I', Keys.SPACE,'Love',Keys.SPACE,'AutoTesting') sleep(5) dr.quit()