自动化测试之 selenium

tsvico Lv5

关于自动化测试的一种插件,记录一下

selenium 是一个用于 Web 应用程序测试的工具。Selenium 测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括 IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera 等。这个工具的主要功能包括:测试与浏览器的兼容性 —— 测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能 —— 创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl 等不同语言的测试脚本。  selenium 用于爬虫,主要是用来解决 javascript 渲染的问题 

插件安装

java 的安装需要导入相关 jar 包,导入教程

selenium 下载最新版本,在官网下载 —> 下载地址

或者下载 selenium-server-standalone 包在 http://selenium-release.storage.googleapis.com/index.html

java 的一些方法和 Python 类似,写在文末,直达车 —-> 滴滴滴

Python 安装相对简单

1
sudo pip install selenium

驱动安装

由于如果需要使用 selenium 的话,需要为本机配置对应浏览器的驱动,下面以 chomedriver 为例,首先安装 chromedriver,chromedriver 与支持对应的 chrome 版本如下:

附 chromedriver 与 chrome 的对应关系表:

chromedriver 版本支持的 Chrome 版本
v2.40v66-68
v2.39v66-68
v2.38v65-67
v2.37v64-66
v2.36v63-65
v2.35v62-64
v2.34v61-63
v2.33v60-62
v2.32v59-61
v2.31v58-60
v2.30v58-60
v2.29v56-58
v2.28v55-57
v2.27v54-56
v2.26v53-55
v2.25v53-55
v2.24v52-54
v2.23v51-53
v2.22v49-52
v2.21v46-50
v2.20v43-48
v2.19v43-47
v2.18v43-46
v2.17v42-43
v2.13v42-45
v2.15v40-43
v2.14v39-42
v2.13v38-41
v2.12v36-40
v2.11v36-40
v2.10v33-36
v2.9v31-34
v2.8v30-33
v2.7v30-33
v2.6v29-32
v2.5v29-32
v2.4v29-32

使用 WebDriver 在 Chrome 浏览器上进行测试时,需要从 http://chromedriver.storage.googleapis.com/index.html网址中下载与本机 chrome 浏览器对应的驱动程序,驱动程序名为 chromedriver;

chromedriver 的版本需要和本机的 chrome 浏览器对应,才能正常使用;我在 Ubuntu16.04 上测试需要把包移动到 /usr/bin/ 目录,Windows 需要下载后把文件解压,然后放到本机 chrome 浏览器文件路径里,如:C:\Program Files (x86)\Google\Chrome\Application

image

下边写在 Python 中的用法

在 Python 中的用法

基本框架

控制 chrome 浏览器,访问百度,并搜索关键词 Python,获取搜索结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
browser=webdriver.Chrome()
try:
browser.get("https://www.baidu.com")
input=browser.find_element_by_id("kw")
input.send_keys("Python")
input.send_keys(Keys.ENTER)
wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,"content_left")))
print(browser.current_url)
print(browser.get_cookies())
print(browser.page_source)
time.sleep(10)
finally:
browser.close()

详细用法如下:

声明浏览器对象

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
from selenium import webdriver
#声明谷歌、Firefox、Safari等浏览器
browser=webdriver.Chrome()
browser=webdriver.Firefox()
browser=webdriver.Safari()
browser=webdriver.Edge()
browser=webdriver.PhantomJS()

访问页面

1
2
3
4
5
6
7
#_*_coding: utf-8_*_

from selenium import webdriver
browser=webdriver.Chrome()
browser.get("http://www.taobao.com")
print(browser.page_source)
browser.close()

查找单个元素

1
2
3
4
5
6
7
8
9
10
11
#_*_coding: utf-8_*_

from selenium import webdriver
from selenium.webdriver.common.by import By
browser=webdriver.Chrome()
browser.get("http://www.taobao.com")
input_first=browser.find_element_by_id("q")
input_second=browser.find_element_by_css_selector("#q")
input_third=browser.find_element(By.ID,"q")
print(input_first,input_second,input_first)
browser.close()

查找多个元素

1
2
3
4
5
6
7
8
9
10
#_*_coding: utf-8_*_

from selenium import webdriver
from selenium.webdriver.common.by import By
browser=webdriver.Chrome()
browser.get("http://www.taobao.com")
lis=browser.find_element_by_css_selector("li")
lis_c=browser.find_element(By.CSS_SELECTOR,"li")
print(lis,lis_c)
browser.close()

元素的交互操作

对获取到的元素调用交互方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#_*_coding: utf-8_*_
from selenium import webdriver
import time
browser=webdriver.Chrome()
browser.get("https://www.taobao.com")
input=browser.find_element_by_id("q")
input.send_keys("iPhone")
time.sleep(10)
input.clear()
input.send_keys("iPad")
button=browser.find_element_by_class_name("btn-search")
button.click()
time.sleep(10)
browser.close()

交互动作

把动作附加到交互链中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#_*_coding: utf-8_*_
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
from selenium.webdriver.common.alert import Alert
browser=webdriver.Chrome()
url="http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
browser.get(url)
#切换到目标元素所在的frame
browser.switch_to.frame("iframeResult")
#确定拖拽目标的起点
source=browser.find_element_by_id("draggable")
#确定拖拽目标的终点
target=browser.find_element_by_id("droppable")
#形成动作链
actions=ActionChains(browser)
actions.drag_and_drop(source,target)
#执行
actions.perform()
'''
1.先用switch_to_alert()方法切换到alert弹出框上
2.可以用text方法获取弹出的文本 信息
3.accept()点击确认按钮
4.dismiss()相当于点右上角x,取消弹出框
'''
t=browser.switch_to_alert()
print(t.text)
t.accept()
time.sleep(10)
browser.close()

执行 javascript

下面的例子是执行就是,拖拽进度条到底,并弹出提示框

1
2
3
4
5
6
7
#_*_coding: utf-8_*_
from selenium import webdriver
browser=webdriver.Chrome()
browser.get("https://www.zhihu.com/explore")
browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
browser.execute_script("alert('To Button')")
browser.close()

获取元素信息

获取属性

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-
from selenium import webdriver

browser=webdriver.Chrome()
url="https://www.zhihu.com/explore"
browser.get(url)
logo=browser.find_element_by_id("zh-top-link-logo")
print(logo)
print(logo.get_attribute("class"))
browser.close()

获取文本值

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-
from selenium import webdriver

browser=webdriver.Chrome()
url="https://www.zhihu.com/explore"
browser.get(url)
logo=browser.find_element_by_id("zh-top-link-logo")
print(logo)
print(logo.text)
browser.close()

获取 ID、位置、大小和标签名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-
from selenium import webdriver

browser=webdriver.Chrome()
url="https://www.zhihu.com/explore"
browser.get(url)
logo=browser.find_element_by_id("zh-top-link-logo")
print(logo)
#id
print(logo.id)
#位置
print(logo.location)
#标签名
print(logo.tag_name)
#大小
print(logo.size)
browser.close()

等待

隐式等待

当使用了隐式等待执行测试的时候,如果 webdriver 没有在 DOM 中找到元素,将继续等待,超过设定的时间后则抛出找不到元素的异常,换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认时间为 0.

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-
from selenium import webdriver

browser=webdriver.Chrome()
url="https://www.zhihu.com/explore"
browser.get(url)
browser.implicitly_wait(10)
logo=browser.find_element_by_id("zh-top-link-logo")
print(logo)
browser.close()

显示等待

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser=webdriver.Chrome()
url="https://www.taobao.com"
browser.get(url)
wait=WebDriverWait(browser,10)
input=wait.until(EC.presence_of_element_located((By.ID,"q")))
button=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".btn-search")))
print(input,button)
browser.close()

浏览器的前进和后退

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
from selenium import webdriver
import time

browser=webdriver.Chrome()
browser.get("https://www.taobao.com")
browser.get("https://www.baidu.com")
browser.get("https://www.python.org")
browser.back()
time.sleep(1)
browser.forward()
browser.close()

cookies 的处理

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
from selenium import webdriver
import time

browser=webdriver.Chrome()
browser.get("https://www.zhihu.com/explore")
print(browser.get_cookies())
browser.add_cookie({"name":"name","domain":"www.zhihu.com","value":"germey"})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())
browser.close()123456789101112

选项卡管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-
from selenium import webdriver
import time

browser=webdriver.Chrome()
browser.get("https://www.zhihu.com/explore")
browser.execute_script("window.open()")
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get("https://www.taobao.com")
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get("https://python.org")
browser.close()1234567891011121314

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException

browser=webdriver.Chrome()
try:
browser.get("https://www.zhihu.com/explore")
except TimeoutException:
print("Time out")
try:
browser.find_element_by_id("hello")
except NoSuchElementException:
print("No Element")
finally:
browser.close()

在 java 中的用法

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Test {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","E:\\webDriver\\chromedriverV2.28.exe");//chromedriver服务地址
WebDriver driver =new ChromeDriver(); //新建一个WebDriver 的对象,但是new 的是FirefoxDriver的驱动
driver.get("http://www.baidu.com");//打开指定的网站
driver.findElement(By.id("kw")).sendKeys(new String[] {"hello"});//找到kw元素的id,然后输入hello
driver.findElement(By.id("su")).click(); //点击按扭
try {
/**
* WebDriver自带了一个智能等待的方法。
dr.manage().timeouts().implicitlyWait(arg0, arg1);
Arg0:等待的时间长度,int 类型 ;
Arg1:等待时间的单位 TimeUnit.SECONDS 一般用秒作为单位。
*/
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
/**
* dr.quit()和dr.close()都可以退出浏览器,简单的说一下两者的区别:第一个close,
* 如果打开了多个页面是关不干净的,它只关闭当前的一个页面。第二个quit,
* 是退出了所有Webdriver所有的窗口,退的非常干净,所以推荐使用quit最为一个case退出的方法。
*/
driver.quit();//退出浏览器
}
}

打开一个 url 并获取对应的网页源码

1
2
3
4
String url = "http://www.baidu.com"; 
driver.get(url);
String pageSource = driver.getPageSource();
System.out.println(pageSource);

浏览器窗口最大化

1
driver.manage().window().maximize();

定位某个元素

1
2
3
4
5
6
//根据ID定位元素:
WebElement ele = driver.findElement(By.id("id"));
//根据Class定位元素:
WebElement ele = driver.findElement(By.className("className"));
//根据xpath定位元素:
WebElement ele = driver.findElement(By.xpath("xpath"));

向表单填数据

1
2
3
WebElement ele = driver.findElement(By.id("id"));
ele.clear();
ele.sendKeys("str");

触发元素的点击事件

1
2
WebElement ele = driver.findElement(By.id("id"));
ele.click();

注意

1、使用 find_element_by_xxxx () 方法查找元素时,如果元素找不到,不会返回 null,而是抛出异常,所以需要自己捕获异常。

2、使用 firefox 后,很多选项虽然在浏览器中进行了设置,但是通过 selenium 启动 firefox 后,设置并没有生效,所以这些设置你需要在代 码中添加。

3、使用 WebDriver 点击 Button 元素时,如果 Button 元素其他元素遮住了,或没出现在界面中 (比如 Button 在页面底部,但是屏幕只能显示页 面上半部分),使用 Click () 方法可能无法触发 Click 事件。

  • 标题: 自动化测试之 selenium
  • 作者: tsvico
  • 创建于 : 2018-08-15 19:29:36
  • 更新于 : 2024-06-27 14:07:36
  • 链接: https://blog.tbox.fun/2018/90af9345.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论