Selenium定位的封装

1.在企业级自动化时,为了提升效率,不要每次都编写冗余的定位代码,需要对定位进行封装来提升开发的效率
2.封装思路,把定位的元素比如name,id,与元素值,存储到变量里
3.创建一个方法,包含两个参数,用于接收元素与元素值,在创建一个if…elif 语句判断元素属于那种定位
4.在定位的时候就不需要重复写定位语句,只需要在定位时调用方法传入参数、
5.代码:

from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains

class Login():

    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get("http://www.imooc.com")
        self.driver.find_element_by_id("js-signin-btn").click()

    def loginScript(self):
        username = "用户名"
        emailElement = "email"
        userby = "name"
        userpass = "密码"
        passwordElement ="password"
        passby = "name"
        buttonElement = "moco-btn"
        futtonby = "classname"
        headerElement = "header-avator"
        nameElement = "name"
        sleep(3)
        #定位方法的调用
        user = self.elements(userby, emailElement)
        user.is_displayed()
        password = self.elements(passby, passwordElement)
        password.is_displayed()
        login = self.elements(futtonby, buttonElement)
        login.is_displayed()
        user.send_keys(username)
        password.send_keys(userpass)
        login.click()
        sleep(3)
        header = self.driver.find_element_by_id(headerElement)
        header.is_displayed()
        actions = ActionChains(self.driver)
        actions.move_to_element(header).perform()
        sleep(3)
        userInfo = self.driver.find_element_by_class_name(nameElement).text
        print(userInfo)
        if userInfo == "Kirin1":
            print("登录成功")
        else:
            print("登录失败")

    def elements(self,element, elementvalues):
    """selenium定位的封装"""
        if element == "id":
            f = self.driver.find_element_by_id(elementvalues)
            return f
        elif element == "name":
            f = self.driver.find_element_by_name(elementvalues)
            return f
        elif element == "classname":
            f = self.driver.find_element_by_class_name(elementvalues)
            return  f
        elif element == "xpath":
            f = self.driver.find_element_by_xpath(elementvalues)


my = Login()
my.loginScript()

你可能感兴趣的:(selenium自动化,Python,selenium,自动化,封装,测试)