Selenium测试工具_py脚本编写
selenium python第三方库学习
分类: 第三方库 | 雨园博客 (gaoyuanqi.cn)
1、简介
工具组成:
- selenium1.0:seleniumide,seleniumrc,seleniumGrid
- selenium2.0:SeleniumRc(CS架构软件测试框架,支持多种变成语言)和Webdriver(浏览器的API。各种模块)合并,seleniumGrid(不同主机上建立主节点hub和分支节点node,测试用例可以在不同分支节点上运行。不同节点支持搭建不同测试环境,从而得到同一用例在不同环境下的结果),seleniumIDE(ui用户脚本录制工具,简单脚本可以,复杂的需要自己修改)
- selenium3.0:selenium2.0改进,selenium,webdriver,seleinumgrid
2、seleinum IDE工具操作
去浏览器安装Selenium IDE插件,然后打开插件,创建或打开一个项目,输入项目URL,开始录制操作。进行操作,最后结束操作

-
open:打开网页操作 -
click:点击网页,里面的id是div的id -
type:上一次点击位置输入 生成代码以关键字驱动,采取主谓宾语法
-
target,对谁进行操作 -
command找到之后的操作 -
value键入了什么
软件共四个按键,第三个是单步执行按键,第四个按键条件运行速度(有些脚本跑太快会导致运行失败)

正常selenium需要设置断言

如图设置百度页面断言assert text操作和对应value
seleinum保存后是side文件,支持导出脚本功能(c#,java,python)
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class Test213():
def setup_method(self, method):
self.driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME)
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_213(self):
self.driver.get("https://www.baidu.com")
self.driver.set_window_size(1136, 1020)
self.driver.find_element(By.ID, "kw").click()
self.vars["2222"] = self.driver.find_element(By.ID, "kw").get_attribute("value")
self.driver.find_element(By.ID, "kw").send_keys("123222")
self.driver.find_element(By.CSS_SELECTOR, ".open-homepage-tts").click()
self.driver.find_element(By.CSS_SELECTOR, "html").click()
self.driver.find_element(By.ID, "su").click()
assert self.driver.find_element(By.CSS_SELECTOR, ".hint_PIwZX").text == "百度为您找到相关结果约1,490,000个"
3、seleinum脚本编写_python的selenium三方库
使用python的selenium会出现driver.find_element(By.ID, ‘sb_form_q’). 等操作(click/send_keys)
没有对应的提示原因是,pycharm本身自带selenium,我们引用了他本身自带selenium,而不是引用重新安装的selenium。所以处理方式是将pycharm自带的selenium删掉,然后cmd输入pip install selenium,这样python引入的selenium才是正确的selenium
、源pycharm自带selenium路径,悬停selenium进行查看
自定义写了一个seleinum脚本
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
driver.get('https:\\bing.com')
element = driver.find_element(By.ID, 'sb_form_q')
element.send_keys('WebDriver')
element.submit()
element2 =driver.find_element(By.ID,'est_cn')
assert element2.text =='gun'
print(element2.text)
element3=driver.find_element(By.CLASS_NAME,'b_logo')
print(element3.title)
assert element3.text =='返回到必应搜'
time.sleep(5)
driver.quit()
selenium3.0:selenium关于断言的使用 - anlcy - 博客园 (cnblogs.com)
3.1、网页元素定位方式-python
from selenium.webdriver.common.by import By
wd.find_element(By.ID, 'username').send_keys('byhy')
wd.find_element(By.CLASS_NAME, 'password').send_keys('sdfsdf')
wd.find_element(By.TAG_NAME, 'input').send_keys('sdfsdf')
wd.find_element(By.CSS_SELECTOR,'button[type=submit]').click()
wd.find_element(By.ID,'username').
element4=driver.find_element(By.NAME,'sb_search')
element4=driver.find_element(By.CLASS_NAME,'sb_search')
element4=driver.find_element(By.TAG_NAME,'sb_search')
find_element(By.LINK_TEXT,u"新闻")
find_element(By.PARTIAL_LINK_TEXT,u"新")
find_element_by_xpath("/html/body/div/div[2]/div/div/div/from/span/input")
find_element_by_xpath("//div[x]/form[x]/input[x]")
find_element(by.xpath,"//input[@id='su']")
find_elementh(by.xpath,"//span[@class='bg s_btn_wr']/input")
find_element(by.xpath,"//input[starts-with(@id,'ctrl')]")
element4=driver.find_element(By.CSS_SELECTOR,'.s_ipt')
element4=driver.find_element(By.CSS_SELECTOR,'input')
element4=driver.find_element(By.CSS_SELECTOR,'span>input')
find_element(by.CSS_SELECTOR,"input[autocomplete='off']")
3.2、定位元素后可进行操作-python
cookies相关,列名讲解,正确默认格式
name cookies名称 | value cookies对应值 |
---|
domain 服务器域名(firebox的不能写这个,会报错) | expiry cookies终止日期 | httpOnly 防止脚本脚本攻击 | secure cookies中标记该变量,表明只有当浏览器和server之间通讯是加密的 | path 定义web服务器上那些路径下页面可以获得服务器设置的cookies | |
from selenium.webdriver.common.by
webdriver.get(url)
webdriver.find_element().send_keys()
send_keys('1234')/send_keys(Keys.ENTER)/send_keys(Keys.CONTRL,'v')
webdriver.get_cookies()
webdriver.add_cookies(cookies_dict)
delete_cookie(name)
delete_all_cookies()
webdriver.find_element(By.ID,"passwd-id").send_keys("")
webdriver.find_element(By.ID,"passwd-id").submit()
webdriver.back()(模拟用户点击其浏览器上的“back”按钮)
webdriver.quit()(模拟用户点击弹出窗体或表单标题栏上的”关闭”按钮)
webdriver.refresh()刷新
webdriver.forward()前进
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
url='https:\\www.baidu.com'
driver.get(url)
email=driver.find_element(By.XPATH,"//div[@id='u']/a[3]")
print(email.get_attribute('href'))
3.3、actionChains动作链_模拟鼠标等交互
鼠标移动,按钮动作,按键上下文互动,菜单交互等有作用,可以达成悬停和拖放动作。
采取动作时不会立即执行,会先将动作存储在actionchains对象的队列中,只有调用perfrom(),方法后才会按照队列存储顺序执行
from selenium.webdriver import ActionChains
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
url='https:\\www.baidu.com'
email=driver.find_element(By.XPATH,"//div[@id='u']/a[3]")
actions=ActionChains(driver).actions.move_to_element().click().perform()
email=driver.find_element(By.XPATH,"//div[@id='u']/a[3]")
email2=driver.find_element(By.XPATH,"//form[@id='form']")
ActionChains(driver).click(email)
realease(eamil)
click_and_hold(email)
double_click(email)
context_click(eamil)
drag_and_drop(email,email2)
drag_and_drop_by_offset(source, x, y)
滑块 = driver.find_element_by_class_name('slider')
动作 = ActionChains(driver)
动作.drag_and_drop_by_offset(滑块, 100, 0).perform()
ActionChains(driver).move_by_offset(xoffset, yoffset)
ActionChains(driver).move_to_element(to_element)
ActionChains(driver).key_down(value, element)
ActionChains(driver).perform()
ActionChains(driver).reset_actions()
ActionChains(driver).pause(seconds)
3.4、元素的隐性等待和显性等待处理(执行引发元素不可见异常处理)
浏览器页面没有加载出定位元素会引发元素不可见异常,一般添加等待时间可以解决问题
selenium.common.exceptions.ElementNotInteractableException:
3.4.1、隐性等待
指定一个等待时间,在等待时间内元素被加载出来则返回定位元素(等待页面全部加载完),再去执行下一步操作,超过规定时间再去引发异常
import time
from selenium import webdriver
driver=webdriver.Edge()
driver.implicitly_wait(20)
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
url='https:\\www.baidu.com'
email2=driver.find_element(By.XPATH,"//form[@id='form']").click()
time.sleep(5)
driver.quit()
3.4.2、显性等待
指定一个等待时间,期间内元素被加载出来则返回到定位元素,否则立即执行下一步操作。规定时间内没有定位成功报错
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
wait=webDriverWait(driver,10,0.1)
email=wait.until(EC.presence_of_element_located((By.ID, 'd')))
time.sleep((5))
3.4.3、等待条件设置
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
email2=driver.find_element(By.XPATH,"//form[@id='form']")
EC.title_is(title)
EC.title_contains(title)
EC.url_contains
EC.url_matches(pattern)
EC.url_to_be(url)
EC.url_changes(url)
EC.text_to_be_present_in_element(locator, text_)
EC.text_to_be_present_in_element(email2,'登录')
EC.element_to_be_clickable(locator)
EC.presence_of_element_located(locator)
EC.presence_of_all_elements_located(locator)
EC.visibility_of(element)
EC.visibility_of_any_elements_located(locator)
EC.element_located_to_be_selected(locator)
EC.element_to_be_selected(element)
EC.invisibility_of_element_located(locator)
EC.invisibility_of_element(element)
EC.staleness_of(element)
3.5、iframe元素切换
iframe:通俗就是网页内显示网页
网页有元素iframe,结构与外部网页一致,属于页面的子页面。但是selenium无法直接定位在iframe的元素,为了定位该元素需要先切换到iframe,也就是切换到子页面后才能进行iframe的元素定位
iframe存在多次嵌套的使用可能
from selenium import webdriver
from selenium.webdriver.common.by import By
driver.switch_to.frame('id')
driver.switch_to.frame(2)
driver.switch_to.frame(driver.find_element(By.id,'id'))
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver=webdriver.Edge(service=s)
url='https://ui.ptlogin2.qq.com/cgi-bin/login?appid=614038002&style=9&s_url=https%3A%2F%2Fdld.qzapp.z.qq.com%2Fqpet%2Fcgi-bin%2Fphonepk%3Fcmd%3Dindex%26channel%3D0'
driver.get(url)
login=driver.find_element(By.ID,'u')
login.send_keys('123456')
password=driver.find_element(By.ID,'p')
password.send_keys('aaaaaaa')
driver.find_element(By.ID,'go').click()
time.sleep(2)
driver.switch_to.frame('cap_iframe')
button01=driver.find_element(By.ID,'cap_iframe')
ActionChains(driver).drag_and_drop_by_offset(button01,100,0).perform()
time.sleep(5)
driver.quit()
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver=webdriver.Edge(service=s)
url='https://ui.ptlogin2.qq.com/cgi-bin/login?appid=614038002&style=9&s_url=https%3A%2F%2Fdld.qzapp.z.qq.com%2Fqpet%2Fcgi-bin%2Fphonepk%3Fcmd%3Dindex%26channel%3D0'
driver.get(url)
driver.switch_to.frame('1')
driver.switch_to.frame('2')
driver.switch_to.frame('3')
driver.switch_to.parent_frame()
driver.switch_to.default_content()
3.6、selenium使用js模拟操作
selenium是没有办法实现下拉滚动条,跳出弹窗等js操作,但是支持execute_script()方法传递其他操作模拟执行js
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.gaoyuanqi.cn')
time.sleep(2)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
time.sleep(2)
driver.execute_script('alert("雨园博客")')
driver.quit()
3.7、send_keys模拟按键操作
一般是通过actionchains动作链实现键盘操作,除了向元素传递值方便很少使用他模拟键盘
from selenium.webdriver import Keys
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver=webdriver.Edge(service=s)
url='https://ui.ptlogin2.qq.com/cgi-bin/login?appid=614038002&style=9&s_url=https%3A%2F%2Fdld.qzapp.z.qq.com%2Fqpet%2Fcgi-bin%2Fphonepk%3Fcmd%3Dindex%26channel%3D0'
driver.get(url)
driver.element_find(by.XPATH,"//div[@id='2']").send_keys(Keys.F10)
3.8、Cookies操作
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium import webdriver
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver=webdriver.Edge(service=s)
url='https://ui.ptlogin2.qq.com/cgi-bin/login?appid=614038002&style=9&s_url=https%3A%2F%2Fdld.qzapp.z.qq.com%2Fqpet%2Fcgi-bin%2Fphonepk%3Fcmd%3Dindex%26channel%3D0'
driver.get(url)
driver.get_cookies()
driver.get_cookie(name)
driver.add_cookie(cookie_dict)
driver.delete_cookie(name)
driver.delete_all_cookies()
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
s=Service(executable_path=r'D:\\edgeDriver\\msedgedriver.exe')
url='https:\\www.baidu.com'
driver=webdriver.Edge(service=s)
driver.get(url)
cookies={"name":"testbyprince","value":"sjsjj"}
driver.add_cookie(cookies)
print(driver.get_cookies())
driver.delete_all_cookies()
print(driver.get_cookies())
driver.quit()
cookies相关,列名讲解,正确默认格式
name cookies名称 | value cookies对应值 |
---|
domain 服务器域名(firebox的不能写这个,会报错) | expiry cookies终止日期 | httpOnly 防止脚本脚本攻击 | secure cookies中标记该变量,表明只有当浏览器和server之间通讯是加密的 | path 定义web服务器上那些路径下页面可以获得服务器设置的cookies | |
3.9、selenium的隐藏自身的代理IP
selenium可以通过设置代理ip来隐藏自己的真实ip,使用代理ip访问网站
import time
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
try:
proxy_ip = '123.122.155.139:19630'
options = Options()
options.add_argument('--proxy-server=http://' + proxy_ip)
options.add_argument('--headless')
options.add_argument(
'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
driver = Chrome(options=options)
driver.get('https://www.gaoyuanqi.cn/python-html-1/#more')
time.sleep(3)
driver.save_screenshot('./aaa.png')
driver.quit()
except Exception:
3.10、网页导航栏操作
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
s=Service(executable_path=r'D:\\edgeDriver\\msedgedriver.exe')
url='https:\\www.baidu.com'
driver=webdriver.Edge(service=s)
driver.get(url)
driver.forward()
driver.back()
driver.refresh()
3.11、窗口操作
设置或获取当前测试网页页面的窗口的xy坐标以及宽度高度,窗口最大化等操作
网页的坐标系与计算方式
根据dom鼠标事件,浏览器响应鼠标事件时同时响应如下种坐标
- **pageX和Y,**x相对于整个网页的坐标,实际尺寸比屏幕打,属于绝对坐标,不随着页面滚动发生变化,网页渲染完毕后固定不变
- clientX和Y,相对于当前视图区的区域坐标。如果是iframe的,则是相对于iframe组件的窗口坐标
- offerX和Y,鼠标位置相对于捕获事件的目标节点坐标,就是鼠标点击位置的元素的坐标,没有点击动作默认body元素坐标
- screeX和Y,相对于显示屏幕的坐标
- **largeX和Y,**不是标准的,存在兼容性问题。鼠标点相对于该层布局的顶端和左端坐标,通常情况下与pageXY数值相同,属于所在层内的绝对坐标
上述坐标中,浏览器内核输入的只有ScreenXY(屏幕)和视图坐标(鼠标点击位置相对于浏览器视窗窗口的坐标)这两种,其余都是计算出来的
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
driver.get('https:\\bing.com')
driver.maximize_window()
driver.set_window_size(width, height)
driver.set_window_position(x, y)
driver.set_window_rect(x, y, width, height)
driver.get_window_size()
driver.get_window_position()
driver.get_window_rect()
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
s=Service(executable_path=r"D:\\edgeDriver\\msedgedriver.exe")
driver = webdriver.Edge(service=s)
driver.get('https:\\bing.com')
driver.maximize_window()
print(driver.get_window_size(),driver.get_window_position(),driver.get_window_rect())
driver.set_window_rect(200,400,200,400)
print(driver.get_window_rect())
{'height': 400, 'width': 515, 'x': 200, 'y': 400}
Seleinum Grid分布式测试工具
selenium+unittest看框架学习
(2条消息) Python-Selenium 网页元素定位方式_忆昔如风-CSDN博客_python定位网页元素
unittest — 单元测试框架 — Python 3.10.2 文档
(2条消息) python的unittest中的常用断言方法_kenny_pj的博客-CSDN博客
(2条消息) python:Unittest_断言方法_不怕猫的耗子A-CSDN博客_unittest断言方法
selenium关于断言的使用 - anlcy - 博客园 (cnblogs.com)
选择元素的基本方法 | 白月黑羽 (byhy.net)
Python + Selenium Web自动化 全套教程 自动化测试 软件测试_哔哩哔哩_bilibili
拓展
katalon工具
- 和seleinum类似,但是可以导出python+unittest的脚本
- seleinum是导出pytest测试框架的
python中webdriver被整合到了seleinum库中。
selenium报错
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable:
evant_default&spm=1001.2101.3001.4242.1&utm_relevant_index=3)
(2条消息) python:Unittest_断言方法_不怕猫的耗子A-CSDN博客_unittest断言方法
selenium关于断言的使用 - anlcy - 博客园 (cnblogs.com)
选择元素的基本方法 | 白月黑羽 (byhy.net)
Python + Selenium Web自动化 全套教程 自动化测试 软件测试_哔哩哔哩_bilibili
拓展
katalon工具
- 和seleinum类似,但是可以导出python+unittest的脚本
- seleinum是导出pytest测试框架的
python中webdriver被整合到了seleinum库中。
selenium报错
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable:
所操纵的定位元素是不可见的,定位元素有不可见修饰
|