天天看點

模拟組合鍵 postmessage ctrl+v_[Selenium]17.send keys模拟按鍵輸入

模拟組合鍵 postmessage ctrl+v_[Selenium]17.send keys模拟按鍵輸入

場景

send_keys方法可以模拟一些組合鍵操作,比如ctrl+a等。另外有時候我們需要在測試時使用tab鍵将焦點轉移到下一個元素,這時候也需要send_keys。在某些更複雜的情況下,還會出現使用send_keys來模拟上下鍵來操作下拉清單的情況。

代碼

下面的代碼示範了如何将A多行文本框中的内容清空并複制到B文本框中。

send_keys.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" target="_blank" rel="external nofollow"  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 python is the best language.</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>
           

send_keys.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-

from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.common.keys import Keys

dr = webdriver.Chrome()
file_path =  'file:///' + os.path.abspath('./html/send_keys.html')
dr.get(file_path)

dr.get(file_path)

# copy content of A
dr.find_element_by_id('A').send_keys((Keys.CONTROL, 'a'))
dr.find_element_by_id('A').send_keys((Keys.CONTROL, 'x'))
sleep(1)

# paste to B
dr.find_element_by_id('B').send_keys((Keys.CONTROL, 'v'))
sleep(1)

# # send keys to A
dr.find_element_by_id('A').send_keys('python', Keys.SPACE, 'is',Keys.SPACE, 'the',  Keys.SPACE, 'best')
sleep(2)

dr.quit()