最近要做web自动化,目前我是用的python+selenium的框架来。因为公司的系统需要扫码登录企业微信账户获取授权,要不然进不了系统,就研究了下。最终的实现方式是扫码获取cookie,然后存入yaml文件。后面直接获取cookie就好。因为cookie是有有效期的,后面我问了开发,可以直接在表里更改有效期,我把它设置成永久有效,就解决复用问题啦。
下面是代码

import time

import yaml
from faker import Faker
from selenium import webdriver
from selenium.webdriver.common.by import By


class TestWeworkLogin:

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

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


    def test_save_cookies(self):
        """
        保存cookies
        :return:
        """
        # 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("./cookies.yaml", "w") as f:
            yaml.safe_dump(data=cookies, stream=f)


    def test_get_cookie(self):
        """
        植入cookie跳过登录
        :return:
        """
        # 1.访问企业微信首页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        # 2.获取本地的cookie
        with open("./cookies.yaml", "r") as f:
            cookies = yaml.safe_load(f)
        print(cookies)
        # 3.植入cookie
        for c in cookies:
            self.driver.add_cookie(c)
        # 4.访问企业微信首页
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        time.sleep(5)

    def test_add_member(self):
        """
        添加成员
        :return:
        """
        faker1 = Faker("zh_Cn")
        usnrname = faker1.name()
        acctid = faker1.ssn()
        mobile = faker1.phone_number()
        print(usnrname, acctid, mobile)

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

        # 5.点击添加成员按钮
        self.driver.find_element(By.LINK_TEXT, "添加成员").click()
        # 6.输入用户名
        self.driver.find_element(By.ID, "username").send_keys(usnrname)
        # 7.输入acctid
        self.driver.find_element(By.ID, "memberAdd_acctid").send_keys(acctid)
        # 8.输入手机号
        self.driver.find_element(By.ID, "memberAdd_phone").send_keys(mobile)
        # 9.点击保存
        self.driver.find_elements(By.CSS_SELECTOR, "a.qui_btn.ww_btn.js_btn_save")[0].click()
        time.sleep(2)
        # 10.断言结果
        tips_text = self.driver.find_element(By.ID, "js_tips").text
        assert "保存成功" == tips_text
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐