接着python里面的xlrd模块详解(一)中咱们咱们来举一个实例:html
咱们来举一个从Excel中读取帐号和密码的例子并调用:python
♦1.制做Excel咱们要对以上输入的用户名和密码进行参数化,使得这些数据读取自Excel文件。咱们将Excel文件命名为data.xlsx,其中有两列数据,第一列为username,第二列为password。web
♦2.读取Excel代码以下app
#-*- coding:utf-8 -*-
import xlrd,time,sys,unittest #导入xlrd等相关模块
class Data_Excel(unittest.TestCase):# 封装在Data_Excel类里面方便后面使用
file_addrec = r'C:\Users\liqiang22230\Desktop\date.xlsx' #定义date.xlsx数据维护Excel的路径文件
def open_excel(self,file = file_addrec):#file = file_addrec #注意在class中def中必定要带self
try:#检验文件有没有被获取到
self.data =xlrd.open_workbook(file) return self.data except Exception : print(file) print('eero') def excel_table_byindex(self,file = file_addrec,colnameindex=0,by_index='用户表'): #把这个读取Excel中封装在excel_table_byindex函数中,这时须要三个参数1.文件2.sheet名称,列所在的行数
self.data = xlrd.open_workbook(file)#获取Excel数据
self.table = self.data.sheet_by_name(by_index)#使用sheet_by_name获取sheet页名叫用户表的sheet对象数据
self.colnames = self.table.row_values(colnameindex)#获取行数下标为0也就是第一行Excel中第一行的全部的数据值
self.nrows = self.table.nrows #得到全部的有效行数
list = []#整体思路是把Excel中数据以字典的形式存在字符串中一个字典当成一个列表元素
for rownum in range(1,self.nrows): row = self.table.row_values(rownum)#获取全部行数每一行的数据值
if row: app = {}#主要以{'name': 'zhangsan', 'password': 12324.0},至于字典中有多少元素主要看有多少列
for i in range(len(self.colnames)): #在这个Excel中,列所在的行有两个数据,因此没循环一行就以这两个数据为键,行数的值为键的值,保存在一个字典里
app[self.colnames[i]] = row[i] list.append(app) print(list) return list a = Data_Excel() a.excel_table_byindex() if __name__=="__main__": unittest.main()
执行结果以下:函数
Testing started at 15:47 ... [{'name': 'zhangsan', 'password': 12324.0}, {'name': 'zhangsan', 'password': 12324.0}, {'name': 'lisi', 'password': 923848.0}, {'name': 'lisi', 'password': 923848.0}, {'name': 'wangmazi', 'password': 213123.0}, {'name': 'wangmazi', 'password': 213123.0}] Process finished with exit code 0 Empty test suite.
♦3.调用Excel代码以下:post
def Login(self): listdata = excel_table_byindex("E:\\data.xlsx",0)#传入两个参数1.文件路径2.第一行所在下标 if (len(listdata) <= 0 ):#判断list列表中是否有数据 assert 0 , u"Excel数据异常" for i in range(0 , len(listdata) ):#循环出list中全部的字典 self.driver = webdriver.Chrome() self.driver.get("http://www.effevo.com") assert "effevo" in self.driver.title #点击登陆按钮 self.driver.find_element_by_xpath(".//*[@id='home']/div/div[2]/header/nav/div[3]/ul/li[2]/a").click() time.sleep(1) self.driver.find_element_by_id('passname').send_keys(listdata[i]['username'])#切出list下标下标为i的字典键为username的值 self.driver.find_element_by_id('password').send_keys(listdata[i]['password'])#切出list下标下标为i的字典键为password的值 self.driver.find_element_by_xpath(".//*[@id='content']/div/div[6]/input").click() time.sleep(2)
self.driver.close()
有什么须要纠正的地方请必定要指出来!谢谢啦。ui