利用Selenium多用户同时开启多线程登录博客园

做自动化测试的朋友经常会遇到多终端同时做某一类的操作,最常见的当然要从登录开始做起,下面介绍利用selenium在单个浏览器开启多个线程,同时做用户登录的操作,后面会介绍多进程方式,请小伙伴们继续关注,下面开始上demo代码

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2020/5/11 22:01
 4 # @Author  : Tang Yiwei
 5 # @Email   : 892398433@qq.com
 6 # @File    : test_mult_user_login.py
 7 # @Software: PyCharm
 8 
 9 import threading
10 from time import sleep,time
11 from selenium import webdriver
12 from multiprocessing import current_process
13 
14 
15 def user_login(username,password):
16     """
17     单终端多线程登录
18     :param username:
19     :param password:
20     :return:
21     """
22     url = "https://account.cnblogs.com/signin"
23     driver = webdriver.Chrome(executable_path="E:\PyCharmPro\svn\mbh\drivers\chromedriver.exe")
24     procName = current_process().name
25     print("当前进程:",procName)
26     sleep(1)
27     start = time()
28     print("session_id: " + driver.session_id)
29     try:
30         driver.get(url)
31         driver.maximize_window()
32         driver.find_element_by_id("LoginName").send_keys(username)
33         sleep(1.5)
34         driver.find_element_by_id("Password").send_keys(password)
35         sleep(1.5)
36         driver.find_element_by_id("submitBtn").click()
37     except Exception as e:
38         raise e
39     finally:
40         driver.close()
41         driver.quit()
42     end = time()
43     print("Task run %0.2f seconds." % (end - start))
44 
45 def list_of_groups(list_info, per_list_len):
46     '''
47     将列表分割成指定长度的子列表,每个列表长度为当前测试并发数
48     :param list_info:   列表,需要进行参数化的总列表
49     :param per_list_len:  每个小列表的长度
50     :return:
51     '''
52     list_of_group = zip(*(iter(list_info),) *per_list_len)
53     end_list = [list(i) for i in list_of_group] # i is a tuple
54     count = len(list_info) % per_list_len
55     end_list.append(list_info[-count:]) if count !=0 else end_list
56     return end_list
57 
58 if __name__ == '__main__':
59     userinfo = [
60         {"username": "xiaoming", "password": "123456"},
61         {"username": "dapeng", "password": "11223344"},
62         {"username": "zuxiaobin", "password": "9090990"},
63         {"username": "wangtao", "password": "4556677"}
64     ]
65     threads = []
66     split_user_list = list_of_groups(userinfo,2)  # 这里只需要修改分割的数量即可实现循环登录和并发登录的数量
67     print(split_user_list)
68     for user_list in split_user_list:
69         threads = [threading.Thread(target=user_login, args=(i["username"], i["password"])) for i in user_list]
70 
71         for t in threads:
72             t.start()
73 
74         for t in threads:
75             t.join()

 

posted @ 2020-05-11 23:10  此去经年归来仍是少年  阅读(5458)  评论(1编辑  收藏  举报