【文章末尾给大家留下了大量的福利】
selenium4
selenium2.0=seleium1.0+webdriver
selenium4.0
基于WEB的UI的自动化测试框架 支持主流的编程语言(Python,java,c#,php,js),支持针对主流的浏览器进行UI的自动化测试(EDGE,Chrome,Firefox)。
selenium环境搭建:
1、下载chrome的浏览器
2、pip install selenium
3、下载与浏览器版本匹配的驱动文件
A、查看chrome浏览器的版本(例如:105.0.5195.102)
B、http://chromedriver.storage.googleapis.com/index.html
4、管理员的身份启动driver的程序
5、把它配置到path的环境变量
找到元素的属性,然后才能够定位到它,下来针对它来进行各种UI交互的操作。
8种常用的元素属性:
ID,name,class_name,tag_name,css,xpath,超链接
ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
我们针对这8种元素属性操作方式,都是有不同的方法来进行操作的
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# id:每个元素属性的ID都是唯一的
#针对webdriver进行实例化,同时指定Chrome的浏览器,浏览器首字母大写driver=webdriver.Chrome()
#打开被测试的网站
driver.get('http://www.baidu.com')
time.sleep(1)
#定位到搜索框,ID
driver.find_element(By.ID,'kw').send_keys('猪')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)
#name
driver.find_element(By.NAME,'wd').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)
#class_name
driver.find_element(By.CLASS_NAME,'s_ipt').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)
'''
xpath:使用路径
当使用xpath的时候,ID是动态的,那么使用fullpath(被定位元素属性的完整路径)
'''
driver.find_element(By.XPATH,'//*[@id="kw"]').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)
# css:基于样式
driver.find_element(By.CSS_SELECTOR,'#kw').send_keys('pig')
time.sleep(3)
driver.find_element(By.CSS_SELECTOR,'#su').click()
time.sleep(3)
# 2种类超链接的查询LINK_TEXT,PARTIAL_LINK_TEXT
# 精确超链接匹配
driver.find_element(By.LINK_TEXT,'新闻').click()
time.sleep(3)
#模糊匹配
driver.find_element(By.PARTIAL_LINK_TEXT,'闻').click()
time.sleep(3)
#关闭浏览器
driver.close()
#tagname,单个元素定位、多个元素索引定位
driver=webdriver.Chrome()
driver.get('file:///C:/Users/Administrator/Desktop/tagTest.html')
time.sleep(3)
driver.find_element(By.TAG_NAME,'input').send_keys('admin')
time.sleep(3)
driver.close()
'''
元素定位的分类:
1、单个元素定位:find_element()
2、多个元素定位:find_elements()
有单个为什么还有多个?
这是因为,当开发写的ID,name,class_name一模一样的时候,这个时候无法区分,
那么只能使用多个元素定位的方式。
多个元素定位方式使用?
它获取的对象是一个列表,我们可以被定位的元素属性在列表中是第几位,根据它的
索引信息来定位它。
'''
driver=webdriver.Chrome()
driver.get('https://baidu.com/')
time.sleep(2)
tags=driver.find_elements(By.TAG_NAME,'input')
print(type(tags))
for item in tags:
print(item)
tags[7].send_keys('pug')
time.sleep(2)
driver.close()
driver=webdriver.Chrome()
driver.get('file:///C:/Users/Administrator/Desktop/tagTest(1).html')
time.sleep(2)
ids=driver.find_elements(By.ID,'asd')
ids[0].send_keys('username')
ids[1].send_keys('passward')
time.sleep(2)
driver.close()
打开网页,点击检查,点击左上角的箭头,将鼠标放入搜索框和百度一下内即可得到元素属性对应的信息
中间有空格的都是错的,所以使用ID
full xpath
css的获取方法
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
'''
先获取当前窗口句柄
然后点击链接,打开一个新的窗口句柄
然后获取到所有的窗口句柄
循环所有的窗口句柄,判断如果不是当前窗口句柄,那么就切换到新的窗口句柄(如果当前的,就只能是新的窗口了)
切换到新的窗口后,进行操作完成后,然后关闭新的窗口,再切换到当前窗口句柄
'''
driver=webdriver.Chrome()
#窗口最大化
driver.maximize_window()
driver.get('https://www.baidu.com/')
time.sleep(1)
#获取当前测试的地址
print(driver.current_url)
#获取当前页面的源码
# print(driver.page_source)
#获取title
print(driver.title)
time.sleep(1)
driver.get('http://news.baidu.com/')
time.sleep(1)
#回退
driver.back()
print(driver.current_url)
time.sleep(1)
#前进
driver.forward()
print(driver.current_url)
time.sleep(1)
driver.close()
driver=webdriver.Chrome()
#窗口最大化
driver.maximize_window()
driver.get('https://www.baidu.com/')
time.sleep(1)
# #获取当前的窗口
nowHandler=driver.current_window_handle
driver.find_element(By.LINK_TEXT,'新闻').click()
time.sleep(2)
#获取所有的窗口
allHandlers=driver.window_handles
#对所有的窗口进行循环
for hander in allHandlers:
if hander!=nowHandler:
#切换到新的窗口
driver.switch_to.window(hander)
time.sleep(2)
driver.find_element(By.ID,'ww').send_keys('百度新闻')
time.sleep(1)
driver.close()
#切换到当前窗口
driver.switch_to.window(nowHandler)
time.sleep(2)
driver.find_element(By.ID,'kw').send_keys('ok')
time.sleep(2)
so=driver.find_element(By.ID,'kw')
so.send_keys('why')
time.sleep(1)
#清理搜索框
so.clear()
#获取属性值
print(so.get_attribute('value'))
print(so.get_attribute('maxlength'))
#是否可见
obj=driver.find_element(By.LINK_TEXT,'关于百度')
print(obj.is_displayed())
#是否可编辑
obj=driver.find_element(By.ID,'kw')
print(obj.is_enabled())
driver.close()
#新浪登录页面自动登录勾选
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://mail.sina.com.cn/')
time.sleep(1)
obj=driver.find_element(By.ID,'store1')
print(obj.is_selected())
time.sleep(2)
obj.click()
time.sleep(1)
print(obj.is_selected())
time.sleep(2)
driver.close()
readonly只读不写
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
'''
下拉框选项:
1、首先对Select进行实例化,这样可以调用里面的方法
2、三种方式:
文本
索引
value值
'''
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('file:///C:/Users/Administrator/Desktop/select(1).html')
time.sleep(1)
sel=driver.find_element(By.ID,'nr')
obj=Select(sel)
time.sleep(1)
#文本模式
# obj.select_by_visible_text('Go语言')
#索引模式
obj.select_by_index(2)
#value值模式
# obj.select_by_value('Go')
time.sleep(2)
driver.close()
#拉勾网的下拉框
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.lagou.com/')
time.sleep(3)
#输入搜索关键字
driver.find_element(By.ID,'search_input').send_keys('测试开发工程师')
time.sleep(1)
driver.find_element(By.ID,'search_button').click()
time.sleep(1)
#点击学历要求
driver.find_element(By.XPATH,'//*[@id="jobsContainer"]/div[2]/div[1]/div[1]/div[2]/div/ul/li[2]/div/span').click()
time.sleep(1)
#选择大专
driver.find_element(By.XPATH,'//*[@id="jobsContainer"]/div[2]/div[1]/div[1]/div[2]/div/ul/li[2]/div/div/ul[2]/li[1]/span').click()
time.sleep(2)
driver.close()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
import time
'''
text:获取弹出框的文本信息
accept是接受Confirm弹出框
dismiss是拒绝接受Confirm弹出框
send_keys是在Prompt消息对话框里面输入想要输入的内容
'''
driver=webdriver.Chrome()
driver.maximize_window()
#警告框
driver.get('file:///C:/Users/Administrator/Desktop/%E8%AD%A6%E5%91%8A%E6%A1%86(2).html')
#获取警告框里面的文本信息
print(driver.switch_to.alert.text)
#点击确定按钮
driver.switch_to.alert.accept()
time.sleep(1)
# 确认消息
driver.get('file:///C:/Users/Administrator/Desktop/%E7%A1%AE%E5%AE%9A%E6%B6%88%E6%81%AF(2).html')
time.sleep(1)
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
driver.switch_to.alert.accept()
time.sleep(1)
# 刷新
driver.refresh()
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
# 点击取消
driver.switch_to.alert.dismiss()
time.sleep(1)
#消息对话框
driver.get('file:///C:/Users/Administrator/Desktop/%E6%B6%88%E6%81%AF%E5%AF%B9%E8%AF%9D%E6%A1%86(2).html')
time.sleep(1)
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
#输入内容
driver.switch_to.alert.send_keys('xc')
time.sleep(1)
driver.switch_to.alert.accept()
time.sleep(2)
driver.close()
'''
ActionChains:主要是针对鼠标事件的处理,在鼠标事件中常用的交互为悬浮,双击,以及右键等操作
如果想使用ActionChains的类,首先需要导入它,导入的命令为:
from selenium.webdriver.common.action_chains import ActionChains
'''
#右键搜索框
driver.get('http://www.baidu.com/')
# 针对ActionChains类进行实例化操作
obj=ActionChains(driver=driver)
time.sleep(2)
so=driver.find_element(By.ID,'kw')
#右键点击搜索框(perform()也是点击的意思,与click()不同)
obj.context_click(so).perform()
time.sleep(1)
driver.close()
# 双击
driver.get('http://www.baidu.com/')
obj=ActionChains(driver=driver)
time.sleep(1)
driver.find_element(By.ID,'kw').send_keys('pug')
button=driver.find_element(By.ID,'su')
#double_click()点击两次百度搜索按钮
obj.double_click(button).perform()
time.sleep(2)
driver.close()
#百度设置
driver.get('http://www.baidu.com/')
obj=ActionChains(driver=driver)
time.sleep(1)
#获取到百度设置的元素属性
settings=driver.find_element(By.XPATH,'//*[@id="s-usersetting-top"]')
#鼠标悬浮到设置按钮
obj.move_to_element(settings).perform()
time.sleep(1)
#点击搜索设置
driver.find_element(By.XPATH,'//*[@id="s-user-setting-menu"]/div/a[1]/span').click()
time.sleep(2)
#点击保存设置
driver.find_element(By.XPATH,'//*[@id="se-setting-7"]/a[2]').click()
time.sleep(2)
print(driver.switch_to.alert.text)
driver.switch_to.alert.accept()
driver.close()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
#键盘事件
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com/')
time.sleep(1)
so=driver.find_element(By.ID,'kw')
so.send_keys('娃哈哈')
time.sleep(1)
so.send_keys(Keys.CONTROL,'a')
time.sleep(1)
so.send_keys(Keys.CONTROL,'c')
time.sleep(1)
so.send_keys(Keys.BACKSPACE)
time.sleep(1)
so.send_keys(Keys.CONTROL,'v')
so.send_keys(1)
driver.close()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as es
from selenium.webdriver.support.ui import WebDriverWait
import time
'''
1、固定等待,也就是使用sleep()方法
2、隐式等待,使用到的方法是implicitly_wait的方法,可以把它理解为设置最长等待时间
3、显式等待,主要指的是程序每隔一段时间执行自定义的程序判断条件,如果判断成立,程序就会继
续执行,那么如果判断失败,就会报TimeOutException的异常信息。
'''
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com/')
driver.implicitly_wait(20)
obj=WebDriverWait(
driver=driver,
timeout=10).until(
method=es.element_to_be_clickable((By.ID,'kw')))
obj.send_keys('cs')
time.sleep(1)
driver.close()
driver.get('https://mail.sina.com.cn/')
driver.implicitly_wait(20)
time.sleep(1)
driver.find_element(By.CLASS_NAME,'loginBtn').click()
obj=WebDriverWait(
driver=driver,
timeout=10).until(
method=es.text_to_be_present_in_element((By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]'),'请输入邮箱名'))
time.sleep(1)
driver.close()
driver.get('http://www.baidu.com/')
driver.implicitly_wait(20)
time.sleep(1)
obj=WebDriverWait(
driver=driver,
timeout=10).until(
method=es.visibility_of_element_located((By.LINK_TEXT,'关于百度')))
print(obj.is_displayed())
obj.click()
time.sleep(1)
driver.close()
'''
iframe的框架,哪些通过方式:
ID
name
索引
当我们使用八种常用元素的方法无法寻找到目标时可能会出现iframe的框架
'''
driver.get('https://file.qq.com/')
driver.implicitly_wait(20)
#进入第一层
# driver.switch_to.frame(0)
driver.switch_to.frame("login_frame1")
time.sleep(1)
#进入到第二层
# driver.switch_to.frame(0)
driver.switch_to.frame('ptlogin_iframe')
time.sleep(1)
driver.find_element(By.XPATH,'//*[@id="switcher_plogin"]').click()
time.sleep(1)
driver.close()
import yaml from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as es from selenium.webdriver.support.ui import WebDriverWait import time import json # 浏览器的滑动 driver=webdriver.Chrome() driver.maximize_window() driver.get('http://www.baidu.com/') driver.implicitly_wait(20) driver.find_element(By.ID,'kw').send_keys('测试') driver.find_element(By.ID,'su').click() time.sleep(1) #滑动到浏览器底部 js='var q=document.documentElement.scrollTop=10000' #调用js语言 driver.execute_script(js) time.sleep(2) #滑动到浏览器顶部 js1='var q=document.documentElement.scrollTop=0' driver.execute_script(js1) time.sleep(1) driver.close() #富文本 def richText(driver,content): ''' 实现在富文本里面输入内容 :param driver: webdriver实例化后的对象信息 :param content: 富文本里面需要输入的文字内容 :return: ''' js="document.getElementById('ueditor_0').contentWindow.document.body.innerHTML='{0}'".format(content) driver.execute_script(js) driver=webdriver.Chrome() driver.maximize_window() driver.get('https://uutool.cn/ueditor/') driver.implicitly_wait(20) time.sleep(2) richText(driver=driver,content='自动化测试') time.sleep(3) driver.close() #时间控件 def startTime(driver,content): '''开始时间控件''' js="$(\"input[placeholder='开始时间≥当前时间']\").removeAttr('readonly');" \ "$(\"input[placeholder='开始时间≥当前时间']\").attr('value','{0}')".format(content) driver.execute_script(js) def endTime(driver,content): '''结束时间控件''' js="$(\"input[placeholder='结束时间>开始时间']\").removeAttr('readonly');" \ "$(\"input[placeholder='结束时间>开始时间']\").attr('value','{0}')".format(content) driver.execute_script(js) driver = webdriver.Chrome() driver.maximize_window() driver.get('C:/Users/Administrator/Desktop/Time/index.html') time.sleep(2) startTime(driver=driver,content='2022-12-12 00:00:20') time.sleep(2) endTime(driver=driver,content='2022-12-21 00:11:11') time.sleep(2) driver.close() ''' UI自动化测试主要测试什么? 1、页面交互 2、表单错误提示信息的验证 3、业务场景 数据驱动:在自动化测试中,把测试中的数据分离到文件中, 这样的一个过程叫数据驱动。 JSON:json CSV:csv EXCEL:xlrd pip install xlrd YAML:pyyaml pip install pyyaml mysql:pymysql pip install pymysql json的内容必须要双引号 yaml的文件冒号后必须空格 ''' 创建sina.yaml文件
创建sina.txt文件
def readJson(): return json.load(open('sina.txt', 'r',encoding='utf-8')) print(readJson()) def readYaml(): with open('sina.yaml','r',encoding='utf-8') as f: return yaml.safe_load(f) print(readYaml()) driever=webdriver.Chrome() driever.get('https://mail.sina.com.cn/') driever.implicitly_wait(20) driever.find_element(By.CLASS_NAME,'loginBtn').click() time.sleep(1) jtext=driever.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]') #python原生断言assert assert jtext.text==readJson()['emailFormat'] assert jtext.text==readYaml()['sina']['emailNull'] time.sleep(2) driever.refresh() driever.find_element(By.CLASS_NAME,'username').send_keys('asdasd') driever.find_element(By.CLASS_NAME,'loginBtn').click() time.sleep(1) jtext=driever.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]') # assert jtext.text==readJson()['emailFormat'] assert jtext.text==readYaml()['sina']['emailFormat'] time.sleep(1) driever.close()
#腾讯文件练习
创建tx.json文件
创建tx.yaml文件
#腾讯文件练习 # def TX1(): # return json.load(open('tx.json', 'r', encoding='utf-8')) # print(TX1()) def TX1(): with open('tx.yaml','r',encoding='utf-8') as f: return yaml.safe_load(f) def readYaml(): with open('qq.yaml','r',encoding='utf-8') as z: return yaml.safe_load(z) driver=webdriver.Chrome() driver.maximize_window() driver.get('https://file.qq.com/') driver.implicitly_wait(20) driver.switch_to.frame(0) driver.switch_to.frame(0) driver.find_element(By.ID,'switcher_plogin').click() time.sleep(1) driver.find_element(By.CLASS_NAME,'btn').click() f1=driver.find_element(By.XPATH,'//*[@id="err_m"]') # print(f1.text) # print(TX1()["qqNull"]) assert f1.text==TX1()['tx']['qqNull'] # assert f1.text==TX1()["qqNull"] time.sleep(1) driver.find_element(By.CLASS_NAME,'inputstyle').send_keys('123') driver.find_element(By.ID,'login_button').click() f1=driver.find_element(By.XPATH,'//*[@id="err_m"]') # print(f1.text) # print(TX1()["qqZH"]) assert f1.text==TX1()['tx']["qqZH"] # assert f1.text==TX1()["qqZH"] time.sleep(1) nowHandler=driver.current_window_handle driver.find_element(By.LINK_TEXT,'注册帐号').click() time.sleep(2) #获取所有的窗口 allHandlers=driver.window_handles #对所有的窗口进行循环 for hander in allHandlers: if hander!=nowHandler: #切换到新的窗口 driver.switch_to.window(hander) time.sleep(1) driver.find_element(By.XPATH, '//*[@id="password"]').send_keys('124567890000000') time.sleep(1) driver.find_element(By.ID, 'phone').send_keys('bn') time.sleep(1) driver.find_element(By.ID, 'get_acc').click() time.sleep(1) devTest1 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[1]/div[3]/div') devTest2 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[2]/div[4]/div') devTest3 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[3]/div[2]/div') devTest4 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[4]/div[2]/div') devTest5 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[6]/div/div') time.sleep(2) assert devTest1.text == readYaml()["qq"]["qqname"] assert devTest2.text == readYaml()["qq"]["password"] assert devTest3.text == readYaml()["qq"]["phone"] assert devTest4.text == readYaml()["qq"]["yanzheng"] assert devTest5.text == readYaml()["qq"]["privace"] time.sleep(3) driver.close() driver.switch_to.window(nowHandler) driver.close()
从python语言基础开始,结合完整的自动化企业项目全面教学,涵盖:web自动化、APP自动化、接口自动化、持续集成、性能等