虽然现在已经大概了解了些selenium使用方法,但基本都是以百度搜索为例子。所以现在再使用其他常用的网站来试试。我选的是126的邮箱登录界面。
脚本例子
上脚本:
import time
import unittest
from selenium import webdriver
class test126(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver=webdriver.Chrome()
cls.url=r"https://www.126.com/"
def testLogin(self):
self.driver.get(self.url)
self.driver.find_element_by_id("switchAccountLogin").click()
myframe=self.driver.find_element_by_xpath("//*[contains(@id,'x-URS-iframe')]")
self.driver.switch_to.frame(myframe)
time.sleep(5)
self.driver.find_element_by_xpath("//*[@name='email' and @data-loginname='loginEmail']").clear()
self.driver.find_element_by_xpath("//*[@name='email' and @data-loginname='loginEmail']").send_keys(yourname)
self.driver.find_element_by_xpath("//*[@name='password' and @type='password']").send_keys(yourpassword)
self.driver.find_element_by_id("dologin").click()
time.sleep(10)
@classmethod
def tearDownClass(cls):
cls.driver.quit()
if __name__=="__main__":
unittest.main()
脚本说明
这里仍然使用的是unittest框架来编写的。关于unittest前面章节已经详细说过,这里不再说啦。重点说一下testLogin测试的主要内容:
1、打开126首页:使用get方法打开126邮箱首页https://www.126.com/,默认显示的是手机扫码登录界面
2、点击【密码登录】按钮,打开密码登录界面,语句为:self.driver.find_element_by_id(“switchAccountLogin”).click()
3、切换到用户登录frame,语句为: myframe=self.driver.find_element_by_xpath("//*[contains(@id,‘x-URS-iframe’)]")
self.driver.switch_to.frame(myframe)
4、清空邮箱用户名(防止有默认的用户名)
self.driver.find_element_by_xpath("//*[@name=‘email’ and @data-loginname=‘loginEmail’]").clear()
5、输入邮箱用户名
self.driver.find_element_by_xpath("//*[@name=‘email’ and @data-loginname=‘loginEmail’]").send_keys(yourname )
请用自己的邮箱账户,替换yourname
6、输入密码
self.driver.find_element_by_xpath("//*[@name=‘password’ and @type=‘password’]").send_keys(yourpassword )
请用自己的密码,替换yourpassword
7、点击【登录】按钮
一些问题
脚本经过5次调试后,才终于登陆成功。哎,对小白来说,不容易啊。遇到的主要问题有:
1、这个页面有多个frame,我之前对HTML并不是很熟悉,所以不知道这个情况。后来通过找我买的书《selenium3自动化测试实践》和百度,才知道这么个情况,所以加上了switch_to.frame方法切换到登陆的frame界面,问题解决。
2、页面上有的元素id包含随机生成的数字。
1)比如要切换的frame,id中包含随机的数字,如下图所示

所以找了找书,找到了适合的方法:
myframe=self.driver.find_element_by_xpath("//*[contains(@id,‘x-URS-iframe’)]")
在find_element_by_xpath中,可以使用属性包含的方式定位,这里的意思是,定位到id属性中包含x-URS-iframe的元素。
2)比如邮箱账户输入框,id完全由随机数字组成,id=“auto-id-xxxxxxxxxxx”,如下图所示

在find_element_by_xpath方法中,还支持多几个属性逻辑运算。如本例子中,
self.driver.find_element_by_xpath("//*[@name=‘email’ and @data-loginname=‘loginEmail’]").clear()
使用name和data-loginname同时符合条件的属性进行元素定位。
3、chrome浏览器的开发者工具实在好用,在定位元素时,多亏了这个工具,嘿嘿。
最后给自己鼓个劲,遇到问题不要放弃,多多实践才是。
本文介绍使用Selenium和unittest框架实现126邮箱登录界面的自动化测试过程,包括处理多frame、随机ID等问题。
5040

被折叠的 条评论
为什么被折叠?



