20220508 web自动化测试实战训练营1

课堂ppt

霍格沃兹测试开发

思维导图

selenium思维导图pdf.zip (30.0 KB)
selenium思维导图xmind.zip (6.2 KB)

课堂内容

  • selenium架构

  • selenium运行机制

实战练习

  1. 植入 cookie 登录(参见【Cookie 复用】)

要求:

  • 首次登录,人工扫码,登录成功保存cookie到本地
  • 后续用例,直接读取本地cookie登录

代码形式:可以是一个测试用例,包含2个方法,(1)获取并保存cookie的测试方法;(2)读取并植入cookie的测试方法。

或者自己封装成函数亦可。

参考视频:
image

参考代码:

"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨,请访问:https://ceshiren.com/t/topic/15860'
"""
import time

import yaml
from selenium import webdriver


class TestWeworkLogin:

    def setup_class(self):
        self.driver = webdriver.Chrome()

    def teardown_class(self):
        # self.driver.quit()
        pass


    def test_save_cookies(self):
        """保存cookies"""


        # 1、访问企业微信登录页面
        self.driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx")
        # 2、手工扫码(直接等待)
        time.sleep(10)
        # 3、获取浏览器cookies
        cookies = self.driver.get_cookies()
        print(cookies)

        # 4、保存cookies
        with open("../data/cookies.yaml", "w") as f:
            yaml.safe_dump(data=cookies, stream=f)

    def test_get_cookie(self):
        """植入cookie"""

        # 1、访问企业微信首页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 2、获取本地的cookie
        with open("../data/cookies.yaml", "r") as f:
            cookies = yaml.safe_load(f)
        print(cookies)

        # 3、植入cookie
        for ck in cookies:
            self.driver.add_cookie(ck)

        # 4、访问企业微信首页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
  1. 等待揭晓

课后作业

  • 实现从通讯录页面添加成员的操作
  • 实现添加部门的操作

上次的作业好像都没改

调查问卷

snail:canvas定位

coding=utf-8

author= ‘Jack’

time:2022/5/8

import time
import yaml
from selenium import webdriver

class Test_Add_Contacts():

def setup_class(self):
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()

def teardown_class(self):
    self.driver.quit()

def test_add_contacts(self):
    self.driver.get( "https://work.weixin.qq.com/wework_admin/frame#contacts" )
    cookie = yaml.safe_load( open( "../data/cookie.yaml" ) )
    for c in cookie:
        self.driver.add_cookie(c)
    time.sleep( 3 )
    self.driver.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
    time.sleep(10)
import yaml
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

class TestCookieLogin():
    def setup_class(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(3)
        self.driver.maximize_window()

    def teardown_class(self):
        self.driver.quit()


    # cookie 持久化存储到yaml中
    def test_save_cookie(self):
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 等待人工扫码完成
        time.sleep(20)
        cookie = self.driver.get_cookies()
        print(cookie)
        # 打开文件时添加写入权限(w)
        with open("cookie.yaml", "w") as f:
            yaml.safe_dump(cookie, f)


    # 添加cookie 实现方法
    def test_add_cookie(self):
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # test_get_cookie方法的输入结果记录到cookies 变量
        # 代码格式化快捷键:Ctrl + Alt + L
        cookies = yaml.safe_load(open("cookie.yaml"))
        # 植入cookie
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        #  再次访问企业微信主页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 点击 通讯录
        self.driver.find_element(By.XPATH, "//*[text()='通讯录']").click()
        time.sleep(3)
class TestDeme():
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        self.driver.maximize_window()


    def teardown(self):
        self.driver.quit()

    def get_cookie(self):
        cookie = self.driver.get_cookies()
        return cookie

    def add_cookie(self):
        if yaml.safe_load(open('cookie.yaml')) is None:
            WebDriverWait(self.driver, 30, 0.5).until(
                expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, '.ww_indexImg_AddMember'))
            )
            cookies = self.get_cookie()
            with open('cookie.yaml', 'w', encoding='utf-8') as f:
                yaml.dump(cookies, f)
        else:
            print(yaml.safe_load(open('cookie.yaml')))
            cookies = yaml.safe_load(open('cookie.yaml'))
            for cookie in cookies:
                self.driver.add_cookie(cookie)
            self.driver.get('https://work.weixin.qq.com/wework_admin/frame')

    def waitunit(self, locator):
        WebDriverWait(self.driver, 30, 0.5).until(
            expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, locator))
        )

    def test_demo(self):
        self.add_cookie()
        self.waitunit('.ww_indexImg_AddMember')
        self.driver.find_element(By.CSS_SELECTOR, '.ww_indexImg_AddMember').click()
        sleep(3)

import shelve
from time import sleep

from selenium import webdriver


class TestCookies():
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)

    def teardown(self):
        self.driver.quit()

    def test_baocun_cookies(self):
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        sleep(5)
        db = shelve.open('cookies')
        cookies = self.driver.get_cookies()#把cookies信息写道文件中 key名cookie
        sleep(3)
        db['cookie']=cookies
        db.close()

    # @pytest.mark.skip
    def test_duqu_cookies(self):
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        db = shelve.open('cookies')
        cookies=db['cookie']
        db.close()
        for cookie in cookies:
            if 'expiry' in cookie.keys():#expiry里面有浮点数非法参数,所以可以删除
                cookie.pop('expiry')
            print(cookie)
            self.driver.add_cookie(cookie)
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
"""
@Time   :3:43 下午
@Author :llBai
@decs   :study_practice
"""
import time

import yaml
import os
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class PageBase:
    def __init__(self, driver: WebDriver):
        self.driver = driver


class PageLogin(PageBase):
    """
    登录页面
    """
    _page_url = "https://work.weixin.qq.com/wework_admin/loginpage_wx"

    def goto_index(self):
        """
        跳转首页
        :return:
        """
        self.driver.get(self._page_url)

        if not os.path.exists("resource"):
            os.mkdir("resource")

        if os.path.exists("resource/cookie.yaml"):
            cookie = yaml.safe_load(open("resource/cookie.yaml"))
            for i in cookie:
                self.driver.add_cookie(i)
            self.driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
        else:
            # 扫码登录,等待页面加载
            WebDriverWait(self.driver, 60).until(expected_conditions.url_contains("wework_admin/frame"))

            # 存入cookie
            cookie = self.driver.get_cookies()
            with open("resource/cookie.yaml", "w") as f:
                yaml.safe_dump(cookie, f)

        return PageIndex(self.driver)


class PageIndex(PageBase):
    """
    首页
    """
    pass


class TestCookie:
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(3)

    def teardown(self):
        self.driver.quit()

    def test_login(self):
        PageLogin(self.driver).goto_index()
        time.sleep(3)


if __name__ == '__main__':
    pass
import yaml
from selenium import webdriver
import pytest

class TestCookies:

    def setup_class(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(3)
    # def teardown_class(self):
    #     self.driver.quit()

    def test_getcookie(self):
        self.driver.get('https://work.weixin.qq.com/wework_admin/loginpage_wx')
        cookies = self.driver.get_cookies()
        with open('cookies.yml','w') as f:
            yaml.safe_dump(data=cookies,stream=f)


    def test_usecookie(self):
        pass
    def test_add_people(self):
        textlist = []
        self.test_login()
        self.waitunit('.ww_indexImg_AddMember')
        self.driver.find_element(By.CSS_SELECTOR, '.ww_indexImg_AddMember').click()
        self.waitunit('#username')
        num = random.randint(1000, 9999)
        self.driver.find_element(By.CSS_SELECTOR, '#username').send_keys(f'test1{num}')
        self.driver.find_element(By.CSS_SELECTOR, '#memberAdd_acctid').send_keys(f'1{num}')
        self.driver.find_element(By.CSS_SELECTOR, '#memberAdd_phone').send_keys(f'1351111{num}')
        self.driver.find_element(By.CSS_SELECTOR, '#memberAdd_biz_mail').send_keys('test1')
        self.driver.find_elements(By.CSS_SELECTOR, 'a.qui_btn.ww_btn.js_btn_save')[0].click()
        self.waitunit('.member_colRight_memberTable_td')
        for every in self.driver.find_elements(By.CSS_SELECTOR, '.member_colRight_memberTable_td'):
            textlist.append(every.text)
        assert f'1351111{num}' in textlist
        sleep(3)

添加成员

"""
@Time   :3:43 下午
@Author :llBai
@decs   :study_practice
"""
import time
import yaml
import os
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class PageBase:
    def __init__(self, driver: WebDriver):
        self.driver = driver


class PageLogin(PageBase):
    """
    登录页面
    """
    _page_url = "https://work.weixin.qq.com/wework_admin/loginpage_wx"

    def goto_index(self):
        """
        跳转首页
        :return:
        """
        self.driver.get(self._page_url)

        if not os.path.exists("resource"):
            os.mkdir("resource")

        if os.path.exists("resource/cookie.yaml"):
            cookie = yaml.safe_load(open("resource/cookie.yaml"))
            for i in cookie:
                self.driver.add_cookie(i)
            self.driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
        else:
            # 扫码登录,等待页面加载
            WebDriverWait(self.driver, 60).until(expected_conditions.url_contains("wework_admin/frame"))

            # 存入cookie
            cookie = self.driver.get_cookies()
            with open("resource/cookie.yaml", "w") as f:
                yaml.safe_dump(cookie, f)

        return PageIndex(self.driver)


class PageIndex(PageBase):
    """
    首页
    """
    _page_url = "https://work.weixin.qq.com/wework_admin/frame#index"
    _path_contact = (By.ID, "menu_contacts")
    _path_addmember = (By.CSS_SELECTOR, '.ww_indexImg_AddMember')

    def goto_addmember(self):
        """
        跳转添加成员页面
        :return:
        """
        self.driver.find_element(*self._path_addmember).click()
        return PageAddmember(self.driver)


class PageAddmember(PageBase):
    """
    添加成员页面
    """
    _page_url = "https://work.weixin.qq.com/wework_admin/frame#contacts"
    _path_name = (By.ID, "username")
    _path_id = (By.ID, "memberAdd_acctid")
    _path_tel = (By.ID, "memberAdd_phone")
    _path_finish = (By.CSS_SELECTOR, ".js_btn_save")
    _path_tips = (By.CSS_SELECTOR, ".ww_inputWithTips_WithErr")

    def add_member_success(self, member_name, member_id, member_tel):
        """
        添加成员成功,跳转回通讯录页面
        :param member_name: 姓名
        :param member_id: 账号
        :param member_tel: 手机
        :return: 通讯录页面页面
        """
        self.driver.find_element(*self._path_name).send_keys(member_name)
        self.driver.find_element(*self._path_id).send_keys(member_id)
        self.driver.find_element(*self._path_tel).send_keys(member_tel)
        self.driver.find_element(*self._path_finish).click()

        return PageContact(self.driver)


class PageContact(PageBase):
    """
    通讯录页面
    """
    pass


class TestCookie:
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(3)

    def teardown(self):
        self.driver.quit()

    def test_login(self):
        PageLogin(self.driver).goto_index()
        time.sleep(3)

    def test_addmember_success(self):
        data = ('llbai', '9527', '13122223333')
        PageLogin(self.driver).goto_index().goto_addmember().add_member_success(*data)
        time.sleep(20)


if __name__ == '__main__':
    pass

# @time:2022/5/8 15:03
# @author: tq
import yaml
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class TestCookieLogin():
    def setup_class(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(3)
        self.driver.maximize_window()

    def teardown_class(self):
        self.driver.quit()


    # cookie 持久化存储到yaml中
    def save_cookie(self):
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 等待人工扫码完成
        time.sleep(20)
        cookie = self.driver.get_cookies()
        print(cookie)
        # 打开文件时添加写入权限(w)
        with open("cookie.yaml", "w") as f:
            yaml.safe_dump(cookie, f)


    # 添加cookie 实现方法
    def add_cookie(self):
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # test_get_cookie方法的输入结果记录到cookies 变量
        # 代码格式化快捷键:Ctrl + Alt + L
        cookies = yaml.safe_load(open("cookie.yaml"))
        # 植入cookie
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        #  再次访问企业微信主页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 点击 通讯录
        self.driver.find_element(By.XPATH, "//*[text()='通讯录']").click()
        time.sleep(3)

    def add_contact(self):
        self.driver.find_element(By.LINK_TEXT, '添加成员').click()
        self.driver.find_element(By.NAME, 'username').send_keys("hogwarts")
        self.driver.find_element(By.NAME, 'acctid').send_keys("hogwarts")
        self.driver.find_element(By.ID, 'memberAdd_phone').send_keys("18912345678")
        self.driver.find_element(By.CSS_SELECTOR, 'a.qui_btn.ww_btn.js_btn_save').click()

    def get_add_result(self):
        element = WebDriverWait(self.driver, 10). \
            until(expected_conditions.visibility_of_element_located((By.XPATH, "//*[contains(text(),'保存成功')]")))
        msg = element.text
        return msg

    def test_add_contact(self):
        self.add_cookie()
        self.add_contact()
        result = self.get_add_result()
        assert result == "保存成功"




from selenium import webdriver


class TestAddEmployee:
    def setup_class(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
    def test_addemployee(self):
        self.driver.find_elements_by_xpath('//a[@class="qui_btn ww_btn js_add_member"]')[1].click()
        self.driver.find_element_by_id("username").send_keys("111")
        self.driver.find_element_by_id("memberAdd_acctid").send_keys("111")
        self.driver.find_element_by_link_text("保存")

import shelve
from time import sleep

import pytest
from selenium import webdriver
from selenium.webdriver import TouchActions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


class TestCookies():
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)

    def teardown(self):
        self.driver.quit()

    def test_save_cookies(self):
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        sleep(5)
        db = shelve.open('cookies')
        cookies = self.driver.get_cookies()#把cookies信息写道文件中 key名cookie
        sleep(3)
        db['cookie']=cookies
        db.close()

    # @pytest.mark.skip
    def test_add_cookies(self):
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        db = shelve.open('cookies')
        cookies=db['cookie']
        db.close()
        for cookie in cookies:
            if 'expiry' in cookie.keys():#expiry里面有浮点数非法参数,所以可以删除
                cookie.pop('expiry')
            print(cookie)
            self.driver.add_cookie(cookie)
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')

    def update_page(self):
        number: str = self.driver.find_element(By.CSS_SELECTOR, '.ww_pageNav_info_text').text
        spilt = number.split('/', 1)
        return [int(x) for x in spilt]

    def test_add_member(self):
        self.driver.find_element(By.XPATH,'//*[text()="通讯录"]').click()
        self.driver.find_element(By.XPATH,'//*[text()="添加成员"]').click()
        self.driver.find_element(By.CSS_SELECTOR,'#username').send_keys('yangguoguo')
        self.driver.find_element(By.CSS_SELECTOR,'#memberAdd_english_name').send_keys('A')
        ele=self.driver.find_element(By.CSS_SELECTOR, '#memberAdd_english_name')
        ele.send_keys('9554')
        self.driver.find_element(By.CSS_SELECTOR,'#memberAdd_phone').send_keys(18340833781)
        self.action=TouchActions(self.driver)
        self.action.scroll_from_element(ele,0,10000).perform()
        self.driver.find_element(By.XPATH,'//*[text()="保存"]').click()

        def func(x):
            if self.driver.find_element(By.CSS_SELECTOR,'.member_colRight_memberTable_td').get_attribute('title')=='yangguoguo':
                return self.driver.find_element(By.CSS_SELECTOR,'.member_colRight_memberTable_td').get_attribute('title')
            num1, num2 = self.update_page()[0], self.update_page()[1]
            self.driver.find_element(By.CSS_SELECTOR,'.js_next_page').click()
            if num1 == num2:
                return False, 'no,this value is {} not exist!!!'.format('yangguoguo')
        a=WebDriverWait(self.driver,15).until(func)
        assert a=='yangguoguo'