利用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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM