您的位置:軟件測(cè)試 > 開(kāi)源軟件測(cè)試 > 開(kāi)源功能測(cè)試工具 > Selenium
Selenium+Python參數(shù)化:讀取TXT文件
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2015/12/8 14:58:13 ] 推薦標(biāo)簽:軟件測(cè)試工具 單元測(cè)試工具

  概述
  從Selenium模塊化一文中,可以看出參數(shù)化的必要性,本文來(lái)介紹下讀取外部txt文件的方法。
  如何打開(kāi)文件
  打開(kāi)文件有以下兩個(gè)函數(shù)可以應(yīng)用:
  1、open(file_name,access_mode)
  file_name: 文件路徑及名稱;
  access_mode :訪問(wèn)方式,具體參數(shù)如下,,未提供參數(shù),則默認(rèn)為r:
  · r:表示讀。
  · w:表示寫(xiě)入;
  · a:表示添加;
  · +: 表示讀寫(xiě);
  · b:表示2進(jìn)制訪問(wèn);
  2、file函數(shù)
  file()內(nèi)建函數(shù)它的功能等于open(),如下根據(jù)文檔說(shuō)明可知:
  >>> help(open)
  open(...)
  open(name[, mode[, buffering]]) -> file object
  Open a file using the file() type, returns a file object.  This is the
  preferred way to open a file.  See file.__doc__ for further information.(END)
  讀取英文txt
  接下來(lái)介紹讀取txt文件內(nèi)容的方法,Python中提供了讀取文件的幾種方法,如下;
  · Read() 讀取整個(gè)文件
  · Readlines()按行讀取整個(gè)文件
  · Readeline()按行讀取一行內(nèi)容
  現(xiàn)在假設(shè)讀取的txt文件存儲(chǔ)的是用戶登錄名及密碼的測(cè)試數(shù)據(jù),內(nèi)容如下:
  admin,admin
  guest,guest
  test,test
  那么這種情況比較適合用按行讀取的方式來(lái)獲取文件,如下示例:
#coding:utf-8
import codecs
def str_reader_txt(address):
fp=open(address,'r')
users=[]
pwds=[]
lines=fp.readlines()
for data in lines:
name,pwd=data.split(',')
name=name.strip(' ')
pwd=pwd.strip(' ')
users.append(name)
pwds.append(pwd)
print "user:%s(len(%d))" %(name,len(name))
print "pwd:%s(len(%d))" %(pwd,len(pwd))
return users,pwds
fp.close()
  上述通過(guò)Readlines()按行讀取txt文件內(nèi)容,并且使用split()函數(shù)切割字符串,分別得到用戶名和密碼,需要注意的是讀取出來(lái)的字符有后面的回車符,所以需要strip函數(shù)進(jìn)行過(guò)濾。
  讀取中文txt
  但是實(shí)際測(cè)試過(guò)程中,也有可能需要輸入中文的用戶及密碼,能否測(cè)試通過(guò)?修改測(cè)試文檔txt的用戶名為中文,內(nèi)容如下:
  管理員,admin
  來(lái)賓,guest
  測(cè)試人員,test
  執(zhí)行上述腳本后,結(jié)果如下:

  可以看出,上述的腳本,在進(jìn)行中文處理時(shí),遇到異常,中文字符顯示亂碼,下面提供兩種解決方法:
  方法一
#coding:utf-8
import codecs
def str_reader_txt(address):
fp=open(address,'r')
users=[]
pwds=[]
lines=fp.readlines()
for data in lines:
print type(data)
data=data.decode("gb18030")#處理中文編碼問(wèn)題
print type(data)
name,pwd=data.split(',')
name=name.strip(' ')
pwd=pwd.strip(' ')
users.append(name)
pwds.append(pwd)
print "user:%s(len(%d))" %(name,len(name))
print "pwd:%s(len(%d))" %(pwd,len(pwd))
return users,pwds
fp.close()

上一頁(yè)12下一頁(yè)
軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd