selenium自动化测试-登录网站用户

昨天学习了selenium自动化测试工具的入门,知道了Selenium是用于自动化控制浏览器做各种操作,打开网页,点击按钮,输入表单等等。

今天学习通过selenium自动化测试工具自动登录某网站用户操作。

第一步:确定目标网址

比如:天天基金网站登录页面"https://login.1234567.com.cn/login"

第二步:确定登录表单元素位置

通过谷歌浏览器F12调试功能可以很快的定位页面元素位置,这也是开发常用谷歌浏览器的原因吧!

比如:用户账号输入框位置

 

 

 

通过 F12 调试确定元素位置,然后右键--》Copy--》Copy XPath: 获得账号输入框位置: //*[@id="tbname"]

在后面写代码操作该元素使用该方法即可:  driver.find_element(By.ID, "tbname")

依次类推,获取密码,记住交易账号单选框,已阅读单选框,登录按钮等等表单元素位置。

 

第三步:编写代码

采用拆分步骤细化功能模块封装方法编写代码,便于后续扩展功能模块。

ttjj_webdriver.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# -*- coding: UTF-8 -*-
# selenium 自动化测试工具
import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
 
 
# 打开驱动
def open_driver():
    try:
        # 连接浏览器web驱动全局变量
        global driver
        # Linux系统下浏览器驱动无界面显示,需要设置参数
        # “–no-sandbox”参数是让Chrome在root权限下跑
        # “–headless”参数是不用打开图形界面
        '''
        chrome_options = Options()
        # 设为无头模式
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--disable-dev-shm-usage')
        # 连接Chrome浏览器驱动,获取驱动
        driver = webdriver.Chrome(chrome_options=chrome_options)
        '''
 
        # 此步骤很重要,设置chrome为开发者模式,防止被各大网站识别出来使用了Selenium
        options = Options()
        # 去掉提示:Chrome正收到自动测试软件的控制
        # options.add_argument('disable-infobars')
        # 以键值对的形式加入参数,打开浏览器开发者模式
        # options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 打开浏览器开发者模式
        # options.add_argument("--auto-open-devtools-for-tabs")
        driver = webdriver.Chrome(chrome_options=options)
 
        # driver = webdriver.Chrome()
        print('连接Chrome浏览器驱动')
        # 浏览器窗口最大化
        driver.maximize_window()
        '''
        1, 隐式等待方法
        driver.implicitly_wait(最大等待时间, 单位: 秒)
        2, 隐式等待作用
        在规定的时间内等待页面所有元素加载;
        3,使用场景:
        在有页面跳转的时候, 可以使用隐式等待。
        '''
        driver.implicitly_wait(3)
        # 强制等待,随机休眠 暂停0-3秒的整数秒,时间区间:[0,3]
        time.sleep(random.randint(0, 3))
 
    except Exception as e:
        driver = None
        print(str(e))
 
 
# 关闭驱动
def close_driver():
    driver.quit()
    print('关闭Chrome浏览器驱动')
 
 
# 检查元素是否存在
def check_element_exists(condition, element):
    '''
    @方法名称: 校验判断网页元素是否存在
    @中文注释: 校验判断网页元素是否存在
    @入参:
        @param condition str 网页元素定位条件
        @param element str 网页元素定位坐标
    @出参:
        @返回状态:
            @return 0 失败
            @return 1 成功
            @return 2 异常
        @返回错误码
        @返回错误信息
    @作    者: PandaCode辉
    @创建时间: 2023-09-21
    @使用范例: check_element_exists('id', 'username')
    '''
    try:
        if (not type(condition) is str):
            print('条件参数错误,不是字符串:' + element)
            return [0, "111111", "条件参数错误,不是字符串", [None]]
        if (not type(element) is str):
            print('元素参数错误,不是字符串:' + element)
            return [0, "111112", "元素参数错误,不是字符串", [None]]
        # 根据条件定位元素
        if condition == 'class':
            driver.find_element(By.CLASS_NAME, element)
        elif condition == 'id':
            driver.find_element(By.ID, element)
        elif condition == 'xpath':
            driver.find_element(By.XPATH, element)
        return [1, '000000', "判断网页元素成功", [None]]
    except Exception as e:
        return [0, '999999', "判断网页元素是否存在异常," + str(e), [None]]
 
 
def pc_ttjj_login(username, password):
    '''
    @方法名称: 登录天天基金用户
    @中文注释: 登录天天基金用户
    @入参:
        @param username str 登录用户
        @param password str 登录密码
    @出参:
        @返回状态:
            @return 0 失败或异常
            @return 1 成功
        @返回错误码
        @返回错误信息
    @作    者: PandaCode辉
    @创建时间: 2023-09-21
    @使用范例: ['user123','pwd123']
    '''
    try:
 
        if (not type(username) is str):
            return [0, "111111", "登录用户参数类型错误,不为字符串", [None]]
        if (not type(password) is str):
            return [0, "111112", "登录密码参数类型错误,不为字符串", [None]]
 
        print('开始打开Chrome浏览器驱动')
        open_driver()
 
        print('随机休眠')
        # 随机休眠 暂停0-2秒的整数秒
        time.sleep(random.randint(0, 2))
 
        print('username:' + username + '/password:' + password)
 
        # 登录时请求的url
        login_url = 'https://login.1234567.com.cn/login'
        driver.get(login_url)
 
        print('随机休眠')
        # 随机休眠 暂停0-2秒的整数秒
        time.sleep(random.randint(0, 2))
 
        # 清空登录框
        # 通过webdriver对象的find_element_by_xx(" "),在selenium的4.0版本中此种用法已经抛弃。
        # driver.find_element_by_xpath("./*//input[@id='tbname']").clear()
        '''
        通过webdriver模块中的By,以指定方式定位元素
        导入模块:from selenium.webdriver.common.by import By
 
         driver.find_element(By.ID,"username")
         driver.find_element(By.CLASS_NAME,"passwors")
         driver.find_element(By.TAG_NAME,"imput"
        '''
        driver.find_element(By.ID, "tbname").clear()
        print('输入用户名')
        # 自动填入登录用户名
        # driver.find_element_by_xpath("./*//input[@id='tbname']").send_keys(username)
        driver.find_element(By.ID, "tbname").send_keys(username)
 
        print('随机休眠')
        # 随机休眠 暂停0-2秒的整数秒
        time.sleep(random.randint(0, 2))
 
        # 清空密码框
        driver.find_element(By.ID, "tbpwd").clear()
        print('输入密码')
        # 自动填入登录密码
        driver.find_element(By.ID, "tbpwd").send_keys(password)
 
        print('随机休眠')
        # 随机休眠 暂停0-2秒的整数秒
        time.sleep(random.randint(0, 2))
 
        # 点击#记住交易帐号
        driver.find_element(By.ID, "tbcook").click()
        print('点击记住交易帐号')
 
        # 点击#同意服务协议
        driver.find_element(By.ID, "protocolCheckbox").click()
        print('点击同意服务协议')
 
        # 点击登录按钮进行登录
        driver.find_element(By.ID, "btn_login").click()
        print('点击登录按钮')
        # 等待3秒启动完成
        driver.implicitly_wait(3)
        time.sleep(3)
 
        print('随机休眠')
        # 随机休眠 暂停0-2秒的整数秒
        time.sleep(random.randint(0, 2))
 
        # 检查元素是否存在,查看持仓明细元素,用来判断是否登录成功
        check_rsp = check_element_exists('id', "myassets_hold")
        if check_rsp[0] == 1:
            print("登录成功")
            print('开始关闭Chrome浏览器驱动')
            close_driver()
            # 返回容器
            return [1, '000000', "登录成功", [None]]
        else:
            return check_rsp
 
    except Exception as e:
        print("登录账户异常," + str(e))
        print('开始关闭Chrome浏览器驱动')
        close_driver()
        return [0, '999999', "登录账户异常," + str(e), [None]]
 
 
# 主方法
if __name__ == '__main__':
    username = "123456789"
    password = "password123"
 
    # 登录用户
    rst = pc_ttjj_login(username, password)

 

第四步:运行测试效果

 

 

-------------------------------------------end---------------------------------------

 

posted @   PandaCode辉  阅读(308)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示