8、Selenium + Python 实现 UI 自动化测试-操作浏览器标签

来源:互联网 发布:muji值得买的东西 知乎 编辑:程序博客网 时间:2024/05/29 03:14

一、概览

想想平时我们都对浏览器标签做过哪些操作?新建,关闭,切换等等


二、了解浏览器窗口和标签页快捷键

百度搜索下关键词,或者看下这篇文章:https://wenku.baidu.com/view/950f30126c175f0e7cd13780.html


三、实例

本节学会 Webdriver 对浏览器标签的常用操作



1、通过快捷键打开浏览器标签

验证:首先手动的打开Chrome浏览器,然后按ctrl+t,成功新建一个tab页,使用ctrl+w,成功关闭一个tab页。快捷键果然有效。


(1)测试了Chrome 浏览器、Firefox浏览器并未成功(哪位小伙伴成功了可以告知下)

ActionChains(driver).key_down(Keys.CONTROL).send_keys("t").key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).send_keys("w").key_up(Keys.CONTROL).perform()


这是我的selenium版本:

C:\Users\admin>pip show selenium
Name: selenium
Version: 3.4.3
Summary: Python bindings for Selenium
Home-page: https://github.com/SeleniumHQ/selenium/
Author: UNKNOWN
Author-email: UNKNOWN
License: Apache 2.0
Location: c:\python36\lib\site-packages
Requires:


(2)使用js 操作(成功)

#使用js打开新标签js="window.open('http://www.sina.com.cn/')"driver.execute_script(js)

2、通过句柄,在标签之间切换

from selenium import webdriverfrom time import sleepdriver = webdriver.Chrome()#第一个标签页打开百度url = "http://www.baidu.com"driver.get(url)#A=百度,当前窗口current_window_handle = driver.current_window_handle#使用js打开新标签#B=163邮箱,现在当前窗口是163邮箱js="window.open('http://mail.163.com/')"driver.execute_script(js)all_window_handles = driver.window_handlessleep(2)for handle in all_window_handles:    if handle == current_window_handle: #切换回第一个窗口        driver.switch_to.window(handle)sleep(2)driver.quit()
需要确定的是当前活动标签页是哪个?要跳到哪个标签去?然后写for循环里面的逻辑


总结:

1、Selenium Webdriver 使用快捷键操作浏览器标签失败;

2、使用 js 新建浏览器标签成功;

3、通过句柄切换浏览器标签成功;


资源:

Firefox Webdriver 下载地址:https://github.com/mozilla/geckodriver/releases

阅读全文
0 0
原创粉丝点击