Selenium 进行参数化

Selenium参数化分为大小:

小:list、dict、函数

大:txt、excel、mysql、redis

哪种方式使自己的工作简单高效就选那种!!!

 

Selenium进行参数化有多种形式:

本文全部以百度为例

一、把需要的参数写在一个txt文档中进行遍历,示例如下

 1 #引入所需包
 2 import time,codecs
 3 from selenium.webdriver.common.by import By
 4 from selenium import webdriver
 5 
 6 #把打开的文档内容进行utf-8编码
 7 source = codecs.open("123.txt","r","utf-8")
 8 value = source.readlines()
 9 # print(list(value))
10 
11 #遍历txt文档中的内容
12 for search in value:
13     driver = webdriver.Chrome()
14     url = "https://www.baidu.com/"
15     driver.get(url)
16     driver.find_element(By.ID,"kw").send_keys(search)
17     time.sleep(3)
18     driver.find_element(By.ID,"su").click()
19     driver.quit()

 二、把需要的参数写在一个函数中,需要的时候进行调用,示例如下

函数部分

1 def fun(user="hanxiaobei",pswd="123456"):
2     print(u"调用函数成功")
3     return user,pswd

代码部分

 1 from selenium.webdriver.common.by import By
 2 from selenium import webdriver
 3 import time
 4 import k1
 5 c2,c3=k1.fun()
 6 # print(k2,k3) #打印是否调用成功
 7 
 8 driver = webdriver.Chrome()
 9 url = "https://www.baidu.com/"
10 driver.get(url)
11 driver.find_element(By.LINK_TEXT,"登录").click()
12 time.sleep(3)
13 driver.find_element(By.ID,"TANGRAM__PSP_10__userName").send_keys(c2)
14 driver.find_element(By.ID,"TANGRAM__PSP_10__password").send_keys(c3)
15 time.sleep(20)  #由于需要输入验证码,我采用的手动输入,嘎嘎
16 driver.find_element(By.ID,"TANGRAM__PSP_10__submit").click()
17 time.sleep(5)
18 driver.quit()

 三、把需要的参数写在字典中,需要的时候进行调用,示例如下

字典写成了一个函数,如下

1 def zidian():
2     data = {"han":"Hanxiaobei","user":123456,"hanxiaobei1":"1234567890"}
3     return data

遍历字典代码部分,如下

 1 from selenium.webdriver.common.by import By
 2 from selenium import webdriver
 3 import time
 4 import k1
 5 info=k1.zidian()
 6 # print(info)
 7 for username,passwd in info.items():
 8     print(username)
 9     print(passwd)
10     driver = webdriver.Chrome()
11     url = "https://www.baidu.com/"
12     driver.get(url)
13     driver.find_element(By.LINK_TEXT,"登录").click()
14     time.sleep(3)
15     driver.find_element(By.ID,"TANGRAM__PSP_10__userName").send_keys(username)
16     driver.find_element(By.ID,"TANGRAM__PSP_10__password").send_keys(passwd)
17     time.sleep(20)
18     driver.find_element(By.ID,"TANGRAM__PSP_10__submit").click()
19     time.sleep(5)
20     driver.quit()

 四、可以把需要的参数写在Excel中,进行遍历取值

关于操作Excel的模块和方法参考我之前写的:http://www.cnblogs.com/hanxiaobei/p/6565587.html

posted @ 2017-08-10 17:29  韩凯1202  阅读(3722)  评论(0编辑  收藏  举报