测试工作存在大量重复性,尤其是回归测试。为了避免新功能,造成不可预料的影响,最好是整个系统流程走一遍,这样自动化测试就显得非常重要。
1. python安装
selenium支持采用java、.net、JavaScript、python、Perl等多种方式编写自动脚本。python语法简洁,这里推荐使用python。
python目前主流版本分为python2和python3使用selenium必需安装python3才行。官网下载python3,安装即可,注意安装时勾选 “添加到path环境变量"或者 ”Add Python3.5 to PATH“。
2. selenium安装
成功安装python后,安装selenium 直接执行 pip install -U selenium 即可。
安装完selenium 后,为了使其能够自动操作浏览器,还需安装浏览器driver,推荐Google chrome浏览器。下载chrome驱动 ,下载页面有很多版本选择,driver版本需要和支持浏览器版本一致才行。driver自版本2.9后,最新版的驱动已经和浏览器版本一致。
查看浏览器版本:帮助--关于chrome 查询chrome版本为74.0.3729下载对应的驱动即可。

下载对应版本的chrome驱动,文件是exe格式,找个目录保存存放该文件即可。为了让selenium脚步能够使用驱动,需要把path to chromedrive.exe path 添加到环境变量 。

3. 脚本编写
安装好selenium 及chrome浏览器驱动后,我们可以编写一个测试脚本,使用selenium操作chrome浏览器,在百度里搜索一下cheese! 代码如下
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
# Create a new instance of the Firefox driver
driver = Chrome()
# go to the google home page
driver.get("http://www.baidu.com")
# the page is ajaxy so the title is originally this:
print(driver.title)
# find the element that's name attribute is q (the google search box)
#inputElement = driver.find_element_by_name("q")
searchBox = driver.find_element(by=By.ID,value='kw')
# type in the search
searchBox.send_keys("cheese!")
# submit the form (although google automatically searches now without submitting)
searchBox.submit()
try:
# we have to wait for the page to refresh, the last thing that seems to be updated is the title
WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))
# You should see "cheese! - Google Search"
print(driver.title)
finally:
driver.quit()
4、 运行脚本
复制上面代码到,到D:\test\hello_seleninum.py 保存文件。
打开cmd ,依次执行下面的操作:
d:
cd d:\test
python hello_seleninum.py
可以看到浏览器被自动打开,然后进入百度,并搜索cheese!


提示消息对话(prompt)
提示消息框提供了一个文本字段,用户可以在此字段输入一个答案来响应您的提示。该消息框有一个"确定"按钮和一个"取消"按钮。选择"确认"会响应对应的提示信息,选择"取消"会关闭对话框。
selenium 提供switch_to_alert()方法定位到 alert/confirm/prompt对话框。使用 text/accept/dismiss/send_keys 进行操作,这里注意的是send_keys只能对prompt进行操作。
switch_to_alert() #定位弹出对话
text() #获取对话框文本值
accept() #相当于点击"确认"
dismiss() #相当于点击"取消"
读取配置文件:
import configparser
from until.file_system import get_init_path
conf = configparser.ConfigParser()
file_path = get_init_path()
print('file_path :',file_path)
conf.read(file_path)
sections = conf.sections()
print('获取配置文件所有的section', sections)
options = conf.options('mysql')
print('获取指定section下所有option', options)
items = conf.items('mysql')
print('获取指定section下所有的键值对', items)
value = conf.get('mysql', 'host')
print('获取指定的section下的option', type(value), value)

网友评论