selenium3 web自动化测试框架 :页面基础操作、元素定

2020-09-15  本文已影响0人  蜀山客e
学习目的:

掌握自动化框架中需要的一些基础web操作

正式步骤:

使用title_contains检查页面是否正确

# -*-  coding:utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

dr = webdriver.Chrome()
url = "https://www.baidu.com"
dr.get(url)
#校验title是否包含校验的内容
a = EC.title_contains("百度一下,你就知道")
#如果包含括号内的内容,则会打印
if a:
    print("title正确")
time.sleep(3)
dr.close()

使用Expected_conditions判断元素是否可见

# -*-  coding:utf-8 -*-

import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

url = "http://www.5itest.cn/register"
dr = webdriver.Chrome()
dr.get(url)
time.sleep(3)
EC.title_contains("注册")

#注册输入操作,如果用element直接传参到WebDriverWait会报错,提示需要传入一个可迭代对象,而不是webelement,所以传入locator
element = dr.find_element_by_xpath('//*[@id="register_email"]')
locator = (By.XPATH,'//*[@id="register_email"]')
WebDriverWait(dr,10).until(EC.visibility_of_element_located(locator))
element.send_keys("111@163.com")

time.sleep(3)
dr.close()

获取定位的标签属性或者输入的内容

# -*-  coding:utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

url = "http://www.5itest.cn/register"
dr = webdriver.Chrome()
dr.get(url)
time.sleep(3)
EC.title_contains("注册")

email_element = dr.find_element_by_xpath('//*[@id="register_email"]')
#打印定位了email的标签其他元素属性
print(email_element.get_attribute("placeholder"))
email_element.send_keys("test@163.com")
#获取输入的内容,查看是否输入正确
text = email_element.get_attribute("value")
assert text == "test@163.com"

time.sleep(1)
dr.quit()

随机生成数据:用户名、邮箱账号

# -*-  coding:utf-8 -*-
import random
import time
from selenium import webdriver

url = "http://www.5itest.cn/register"
dr = webdriver.Chrome()
dr.get(url)
time.sleep(3)
#Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
data_email = ''.join(random.sample("123456789abcdefg",6))+'@163.com'
data_name = ''.join(random.sample("AaBbCcDdEeFf",4))
dr.find_element_by_xpath('//*[@id="register_email"]').send_keys(data_email)
dr.find_element_by_xpath('//*[@id="register_nickname"]').send_keys(data_name)
time.sleep(3)
dr.close()

解决验证码--获取验证码图片

# -*-  coding:utf-8 -*-

import time
import random
from PIL import Image
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from  selenium.webdriver.common.by import By
from  selenium.webdriver.support.wait import WebDriverWait

url = "http://www.5itest.cn/register"
dr = webdriver.Chrome()
dr.get(url)
dr.maximize_window()
time.sleep(3)
element_email = dr.find_element_by_xpath('//*[@id="register_email"]')
elemant_name = dr.find_element_by_xpath('//*[@id="register_nickname"]')
elemant_pwd = dr.find_element_by_xpath('//*[@id="register_password"]')
data_email = ''.join(random.sample('asdzxc123456',6))
data_name = ''.join(random.sample('BNMGHJ',4))
locator = (By.XPATH,'//*[@id="register_email"]')
WebDriverWait(dr,10).until(EC.visibility_of_element_located(locator))
element_email.send_keys(data_email+'@163.com')
elemant_name.send_keys(data_name)
elemant_pwd.send_keys('111111')

#图片处理
dr.save_screenshot(r"F:\python_stack\python_autotest\num.png")
element_code = dr.find_element_by_xpath('//*[@id="getcode_num"]')
print(element_code.location)
code_left = element_code.location['x']
code_top = element_code.location['y']
code_right = element_code.size['width']+code_left
code_bottom = element_code.size['height'] + code_top
#打开页面的截图
im = Image.open("F:/python_stack/python_autotest/num.png")
#根据上下左右的坐标,来截取验证码图片
img = im.crop((code_left,code_top,code_right,code_bottom))
img.save("F:/python_stack/python_autotest/num_code.png")

time.sleep(3)
dr.close()

从验证码图片获取验证码

import pytesseract
from PIL import Image

img = Image.open("F:/python_stack/python_autotest/num_code.png")
text = pytesseract.image_to_string(img)
print(text)

PS:

如果报错:tesseract is not installed or it's not in your path

请自己下载一个Tesseract-OCR

重构封装读取配置文件方法

配置文件内容:

[RegisterElement]
element_email=id>register_email
elemant_name=id>register_nickname
elemant_pwd=id>register_password
[/RegisterElement]

读取配置文件代码:

# -*-  coding:utf-8 -*-
'''
pip install Configparser 安装参数解析读取的包
'''

import configparser

class ReadIni(object):
    def __init__(self,filename = None,node= None):
        if filename == None:
            filename = "F:/python_stack/python_autotest/config/LocalElement.ini"
        if node == None:
            self.node = "RegisterElement"
        else:
            self.node = node
        self.cf = self.load_ini(filename)
#加载文件
    def load_ini(self,filename):
        cf = configparser.ConfigParser()
        cf.read(filename)
        return cf
#获取value值
    def get_value(self,key):
        data = self.cf.get(self.node,key)
        return data


if __name__ == "__main__":
    test = ReadIni()
    print(test.get_value("elemant_pwd"))

封装定位元素类 : find_elemnet.py

# -*-  coding:utf-8 -*-
from util.ReadIni import ReadIni
from selenium import webdriver
 
 
class FindElement(object):
    def __init__(self, driver):
        self.driver = driver
 
    def get_element(self, key):
        readini = ReadIni()
        data = readini.get_value(key)
        by = data.split(">")[0]
        # print(by)
        value = data.split(">")[1]
        # print(value)
        try:
            if by == 'id':
                return self.driver.find_element_by_id(value)
            elif by == "name":
                return self.driver.find_element_by_name(value)
            elif by == "className":
                return self.driver.find_element_by_className(value)
            else:
                return self.driver.find_element_by_xpath(value)
        except:
            return None
 
 
if __name__ == "__main__":
    driver = webdriver.Chrome()
    test = FindElement(driver)
    test.get_element("element_email")

页面注册方法封装示例

# -*-  coding:utf-8 -*-
from util.find_elemnet import FindElement
from selenium import webdriver


class RegisterFunction(object):
    def __init__(self,url):
        self.driver = self.get_driver(url)


    #获取driver,并打开网页
    def get_driver(self,url):
        driver = webdriver.Chrome()
        driver.get(url)
        driver.maximize_window()
        return driver

    #输入用户信息
    def send_user_info(self,key,data):
        self.get_user_element(key).send_keys(data)

    #定位用户的各个element,find_element为find_element.py的实例,然后把实例化的self.driver传入
    #然后find_element就可以正常定位
    def get_user_element(self,key):
        find_element = FindElement(self.driver)
        user_element = find_element.get_element(key)
        return user_element

    def main(self):
        self.send_user_info("element_email","test@163.com")
        self.send_user_info("elemant_name","admin")
        self.send_user_info("elemant_pwd", "111111")


if __name__ == "__main__":
    url = "http://www.5itest.cn/register"
    register = RegisterFunction(url)
    register.main()

总结:

页面的常用方法建议本地建立一个方法库表格,后续直接参考,这个是后续要写的

点赞关注~~持续分享,加入我们,642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。

上一篇下一篇

猜你喜欢

热点阅读