(python + selenium) 数据驱动(参数化)

读取txt文件中的数据来实现参数化

创建data.txt文件

(python + selenium) 数据驱动(参数化)_第1张图片

baidu_readData.py

#-*- coding:utf-8 -*-

from selenium import webdriver
import os,time

source = open("C:\Python27\example\data.txt","r")
values = source.readlines()
source.close()

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
	
for val in values:
	driver.find_element_by_id("kw").clear()
	driver.find_element_by_id("kw").send_keys(val)
	driver.find_element_by_id("su").click()
	time.sleep(3)
	
driver.quit()
	

登录参数化(读取txt文件)

按照上面的思路,对自动化脚本中用户名、密码进行参数化,通过Python文档我们发现读取文件的方式有:整个文件读取、逐行读取、固定字节读取。并没有找到一次读取两条数据的好方法。

创建data.txt文件

(python + selenium) 数据驱动(参数化)_第2张图片

login_douban_by_txt.py

#-*- coding:utf-8 -*-

from selenium import webdriver
import os,time

source = open("C:\Python27\example\data.txt","r")
values = source.readlines()
source.close()

for val in values:
	if "username" in val:
		un = val.split('=')[1:]
	elif "password" in val:
		pw = val.split('=')[1:]

print un,pw
driver = webdriver.Chrome()
driver.get("http://www.douban.com")
driver.find_element_by_name("form_email").clear()
driver.find_element_by_name("form_email").send_keys(un)
time.sleep(3)
driver.find_element_by_name("form_password").clear()
driver.find_element_by_name("form_password").send_keys(pw)
time.sleep(3)
driver.find_element_by_class_name("bn-submit").click()
time.sleep(3)		
driver.quit()	

登录参数化(函数)

userinfo.py

def fun(un="15757119427",pw='mailu777333'):
	print "successful read username and password!"
	return un,pw

login_douban_by_function.py

from selenium import webdriver
import hello_selenium,time

un,pw=hello_selenium.fun()

print un,pw

driver = webdriver.Chrome()
driver.get("http://www.douban.com")
driver.find_element_by_name("form_email").clear()
driver.find_element_by_name("form_email").send_keys(un)
time.sleep(3)
driver.find_element_by_name("form_password").clear()
driver.find_element_by_name("form_password").send_keys(pw)
time.sleep(3)
driver.find_element_by_class_name("bn-submit").click()
time.sleep(3)		
driver.quit()	

表单参数化(csv)

创建userinfo.csv文件

(python + selenium) 数据驱动(参数化)_第3张图片

loop_read.py

#-*- coding:utf-8 -*-

#导入csv包
import csv

#读取本地csv文件
my_file="C:\Python27\example\data.csv"
data=csv.reader(file(my_file,'rb'))

#循环输出每一行的内容
for user in data:
	print user[0]
	print user[1]
	print user[2]
	print user[3]

运行结果:

(python + selenium) 数据驱动(参数化)_第4张图片


你可能感兴趣的:(selenium元素定位,python)