学习python下使用selenium2自动测试第6天,参数化编程这节课花了两天时间。

本次编程主要时间是花在熟悉python上

知识点or坑点:

1、读取txt、xml、csv等文件存储的账号、密码

txt文件格式,逗号分割(也可使用其他符号):

www.126.com,user1,pwd1

www.qq.com,user2,pwd2

www.163.com,user3,pwd3

user_file = open('user_info.txt','r')
lines = user_file.readlines()
user_file.close()

for line in lines:
    mail = line.split(',')[0]
    username = line.split(',')[1]
    pwd = line.split(',')[2]
    print(mail,username,pwd)

2、打开多窗口,定位新窗口

获取所有窗口句柄:cur_windows = dr.window_handles

定位窗口:

for cur_window in cur_windows:
  dr.switch_to.window(cur_window)

3、python编程中self的作用

在我的理解中,self是全局的this对象,定义一个class LoginSetup():

self就是指LoginSetup这个对象本身

在本class中定义多个对象时,可使用self.function( [param1,param2,...] )来调用,

被调用方法的参数self为默认参数,真实接收参数从第二个开始

被调用函数:

def open_url(self,url):
        js = 'window.open("'+url+'")'
        print(js)
        self.driver.execute_script(js)

调用函数:

def login(self):
    json_lines = []
    ……
    self.open_login(json_lines)

  

4、python的init初始化,是前后两个下划线横杠(坑点)

#初始化,两个下划横杠
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)
        url = 'http://www.baidu.com'
        self.init_url = url
        self.driver.get(url)

在类运行时,初始化一些参数

5、python的in

for 循环、比较部分字符串都可使用in

foreach:

for line in lines:

     print(line['username'])

  print(line['pwd'])

比较字符串:

if 'QQ' in url:

  print('true')

 

登陆QQ邮箱代码:

 1 from selenium import webdriver
 2 from time import sleep
 3 
 4 class QqLogin():
 5 
 6     def user_login(dr,username,pwd):
 7 
 8         print(username,pwd)
 9         
10         dr.switch_to.frame("login_frame")
11         idInput = dr.find_element_by_id('u')
12         pwdInput = dr.find_element_by_id('p')
13         idInput.clear()
14         idInput.send_keys(username)
15         pwdInput.clear()
16         pwdInput.send_keys(pwd)
17 
18         #登录
19         dr.find_element_by_id('login_button').click()
20 
21         #返回上级frame
22         #dr.switch_to.parent_frame()
23 
24         #返回主frame,此处两个方法都可以
25         dr.switch_to.default_content()
26 
27         #调用返回主frame需要等一下
28         sleep(1)
29 
30         switchs = dr.find_elements_by_css_selector('div')
31         print( len(switchs) )
32 
33         #获取登录用户名、邮箱
34         name = dr.find_element_by_id('useralias')
35         email = dr.find_element_by_id('useraddr')
36         print('qq登录成功|',name.text,'---',email.text)
37 
38         #dr.quit()
View Code

相关文章:

  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2021-04-18
  • 2022-01-15
  • 2021-04-08
  • 2021-08-18
猜你喜欢
  • 2021-10-14
  • 2021-07-05
  • 2021-12-14
  • 2021-12-03
  • 2021-12-02
  • 2021-12-29
  • 2022-02-25
相关资源
相似解决方案