Selenium Keys键盘按键包使用实例

在使用Selenium进行自动化测试过程中,经常需要用到一些键盘操作,Selenium提供一个Keys包来模拟所有的键盘操作,以下是一些使用的实例:

首先要导入:

from selenium.webdriver.common.keys import Keys  #需要引入keys包

1.通过定位密码框,enter(回车)来代替登陆按钮

driver.find_element_by_id("user_pwd").send_keys(Keys.ENTER)

2.ctrl+a 全选输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a')

3.刷新页面

driver.refresh()#刷新页面重新加载(相当于F5)

4.下拉页面(相当于滑动下拉框到底部)

driver.find_element_by_id("kw").send_keys(Keys.PageDown)

5.通过键盘和鼠标操作实现将指定的图片鼠标右键下载保存图片操作

使用selenium模拟鼠标和键盘操作:将鼠标放置图像上方,点击鼠标右键,然后键盘按V就可以保存了,核心代码如下:

from selenium.webdriver.common.action_chains import ActionChains 
from selenium.webdriver.common.keys import Keys

action = ActionChains(driver).move_to_element(element)#移动到该元素
action.context_click(element)#右键点击该元素
action.send_keys(Keys.ARROW_DOWN)#点击键盘向下箭头
action.send_keys('v')#键盘输入V保存图
action.perform()#执行保存

猜你喜欢

转载自blog.csdn.net/longfei_2010/article/details/80266722
今日推荐