pip install -U selenium安装最新版本selenium
安装的依赖,在Mac上不方便配置环境变量
注意浏览器版本,不要升到最新版本
selenium相当于一个模块包,webdriver相当于一个类
from 路径 import 内容
超类即object类
import os,time
import unittest
currentPath = os.path.abspath(os.path.dirname(__file__)) #当前目录
projectPath = os.path.split(currentPath)[0] #取下标
toolsPath = projectPath.replace("\\",'/')+'/driver/chromedriver'
url = 'https://www.baidu.com'
print(currentPath)
print(projectPath)
print(toolsPath)
D:\sdk\tools\untitled4\testcase (上一级文件夹路径,类型为str)
D:\sdk\tools\untitled4
D:/sdk/tools/untitled4/driver/chromedriver
定位到截图目录
toolsPath = projectPath.replace("\\",'/')+'/driver/chromedriver'
class SavePng(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path = toolsPath)
cls.driver.get(url) #成员方法
cls.driver.implicityl_wait(10) #隐式等待
类和类的调用需要实例化
import os,time
import unittest
currentPath = os.path.abspath(os.path.dirname(__file__)) #当前目录
projectPath = os.path.split(currentPath)[0] #取下标
toolsPath = projectPath.replace("\\",'/')+'/driver/chromedriver'
url = 'https://www.baidu.com' #文件的全局变量
print(currentPath)
print(projectPath)
print(toolsPath)
class SavePng(unittest.TestCase):
#不用被实例化,不能当做类变量
@classmethod
def setUpClass(cls):
url = 'https://www.baidu.com' # 局部变量
cls.driver = webdriver.Chrome(executable_path = toolsPath)
cls.driver.get(url) #成员方法
cls.driver.implicityl_wait(10) #隐式等待
ini用于服务器配置
def get_ini_date(secions, items):
iniconf = r"D:\trx\selenium_uses\Conf\config.ini" #路径中出现 \t 字符转义
conf = configparser.ConfigParser() #读取路径实例化
conf.read(iniconf, encoding = "utf-8") #读取方式 转义为utf-8 否则出现gbk问题
return conf.get(sections, items)
注意:return conf.get(sections, items) 与ini文件中的大小写 upper()或lower()
括号内为入参,读取方法get_ini_date(),读取ini文件,被调用 (注意:调用和引用的区别,调用有返回?,没有返回形参没有意义)
self.driver.get(get_ini_date("Url","baidu_url") #入参,实参
class Mytest(unittest.TestCase):
def setUp(self): #初始化
self.driver = browser()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
def tearDown(self): #回收
self.driver.quite()
class demo():
def _time(self, time1, time2): # 类私有,别的类不能被继承,类的成员方法,成员方法
if debug:
time.sleep (time1)
else:
time.sleep (time2)
def test_a_indexUrl(self):
"""
:return:
"""
try:
self._time(5, 10)
tt = client.assert_title("理想生活")
self.assertTrue(tt,msg="判断正确")
if DEBUG:
_logger.info("进入天猫")
except NoSuchElementException as err:
print(format(err))
try:
被保护代码
except .... exception as xxx:
raise xxx
创建base模块
__init__ python包,可被其他模块引用(from base import Err)
class RunTimeOut(Exception):
pass
class AssertErrorOut(Exception):
pass
class TimeOut(Exception):
pass
引用
from base import Err
class Demo(unitTest.TestCase):
def test_a_Tittle(self):
#print("调式title",pc.get_option_value("Title","baidu_tt"))
#res修改了
try:
log._logger.info("验证网站的tittle")
res =commond.assert_title(pc.get_option_value("Title","baidu_tt")) #断言title
self.assertTrue(res,"百度的title验证正确")
except Exception as err:
commond.get_windows_img(r"E:\selenium_uses\Pic\test_a_Tittle")
# print("assertTrue test fail", err)
raise Err.RunTimeOut("assertTrue test fail")from err #调用
网页title,非空字符串
查看方法
from base import Err
class Demo(unittest.TestCase):
def test_a_Tittle(self):
#print("调式title",pc.get_option_value("Title","baidu_tt"))
#res修改了
try:
self.assertEqual("百度一下,你就知道", self.driver.title)
print("assertEqual test pass")
# self.assertTrue(res,"百度的title验证正确")
self.assertTrue(0, msg="这里为0") #####
except Exception as err:
commond.get_windows_img(r"E:\selenium_uses\Pic\test_a_Tittle")
# print("assertTrue test fail", err)
raise Err.RunTimeOut("assertTrue test fail")from err #调用
class Baidu_Api(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver =commond.get_driver("chrome","https://www.baidu.com")
log._logger.info("启动浏览器")
commond.time_sleep(3)
@classmethod
def tearDownClass(cls):
log._logger.info("执行,关闭浏览器")
commond.quit()
class Demo(unittest.Testcase):
def test_findtype_title(self):
try:
print("验证类型",type(self.driver.title))
self.assertIsInstance(self.driver.title,str,"测试对象类型是str类型")
print("asserIsInstance test pass")
except Exception as err:
raise RuntimeError("get元素失败")from err
import unittest
class Demo(unittest.TestCase):
def test_findtype_title(self):
try:
print("验证类型",type(self.driver.title))
t = self.driver.current_url #当前的URL
print("当前是什么",t)
t1 = self.driver.current_url
self.assertEqual(t, "https://www.baidu.com/",msg="当前URL为{}正确".format(t)) #
self.assertIsInstance(self.driver.title,str,"测试对象类型是str类型")
print("asserIsInstance test pass")
except Exception as err:
raise RuntimeError("get元素失败")from err
def test_findtype_title(self):
try:
print("验证类型",type(self.driver.title))
t = self.driver.current_url #当前的URL
print("当前是什么",t)
t1 = self.driver.current_url
self.assertIn("https://www.baidu.com/", t, msg="当前URL为{}正确".format(t)) #assertIn
self.assertIsInstance(self.driver.title,str,"测试对象类型是str类型")
print("asserIsInstance test pass")
except Exception as err:
raise RuntimeError("get元素失败")from err
class Mytest(unittest.TestCase):
@unittest.skip("本次不执行")
def setUp(self):
self.driver = browser()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
@unittest.skipUnless(debug>6,"失败条件不跳出")
def test_admin_login(self):
username = "xx"
password = "xx"
Login().user_login(self.driver, username, password)
@unittest.skipIf(debug<5,"debug全局满足条件")
def test_user_login(self):
username = "www"
password = username
Login().user_login(self.driver, username, password)
定位器识别控件属性
定位元素顺序:
1.id
2.name
3.xpath或css-selector
id(当前页面唯一,即page_source唯一,变换位置也没关系) name (不唯一)
定义一个目录去写入文件,文件拼接
open(前面定义path,“w+”)
启动webdriver.Chrome time.time()
文件关闭 条件
tagname
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
a = driver.find_element_by_tag_name("a")
# a = driver.find_element_by_tag_name("a").text
# print(a)
if a:
print("found a!")
driver.quit()
tagname会拿到很多元素,然后用in去找元素
classname
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
a = driver.get_window_size()
driver.maximize_window()
driver.find_element_by_class_name("soutu-btn").click()
sleep(4)
objsize = self.driver.page_source.__sizeof__() #单位为bytes
print("当前网页大小{}kb".format(int(objsize / 1024)))
time.sleep(2)
if int(objsize / 1024) > 60: # 判断尺寸
print(self.driver.current_url, "该网页尺寸过大")
检查每个浏览器的占用size的比例
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
a = driver.get_window_size()
driver.maximize_window()
cookies = driver.get_cookies()
print("当前窗口尺寸{},缓存cookies为{}".format(a, cookies))
print("value值为{}".format(cookies[0].get("value")))
图片:
断言是字典类型
a.size
from selenium import webdriver
from time import sleep
try:
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
a = driver.get_window_size()
driver.maximize_window()
a = driver.find_element_by_css_selector("#form > span.bg.s_ipt_wr.quickdelete-wrap > span")
print("picture:",a.size, a.text)
driver.find_element_by_css_selector("#form > span.bg.s_ipt_wr.quickdelete-wrap > span").click()
except Exception as error:
print(error)
sleep(4)
link(超文本) text (模糊搜索)
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
driver.find_element_by_link_text("新闻").click()
#driver.find_element_by_partial_link_text("新").click() #可进行模糊查询,不推荐
if "百度新闻" in driver.title:
print("arrive to news page!")
sleep(4)
driver.quit()
from selenium import webdriver
from time import sleep
try:
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
a = driver.get_window_size()
driver.maximize_window()
a = driver.find_element_by_css_selector("#form > span.bg.s_ipt_wr.quickdelete-wrap > span")
print("picture:",a.size, a.text)
driver.find_element_by_css_selector("#form > span.bg.s_ipt_wr.quickdelete-wrap > span").click()
except Exception as error:
print(error)
sleep(4)