Selenium+python自動化21-TXT數據參數化
阿新 • • 發佈:2018-05-12
unit AI [1] 密碼文件 lines val send def 每次
前言
在17篇我們講了excel數據的參數化,有人問了txt數據的參數化該怎麽辦呢,下面小編為你帶你txt數據參數化的講解
一、以百度搜索為例,自動搜索五次不同的關鍵字。輸入的數據不同從而引起輸出結果的變化。
測試腳本:
1 #coding=utf-8 2 from selenium import webdriver 3 import unittest, time, os 4 class Login(unittest.TestCase): 5 def test_login(self): 6 source = open("D:\\test\\txt.txt", "r") 7 values = source.readlines() 8 source.close() 9 # 執行循環 10 for hzy in values : 11 driver=webdriver.Firefox() 12 driver.get("http://www.baidu.com/") 13 driver.maximize_window() 14 driver.find_element_by_id("kw").send_keys(hzy)15 driver.find_element_by_id("su").click() 16 time.sleep(2) 17 driver.close()
txt文件:
open方法以只讀方式(r)打開本地txt.txt文件,readlines方法是逐行讀取整個文件內容。
通過for循環,hzy可以每次獲取到文件中一行數據,在定位到百度輸入框後,將數據傳入send_keys(hzy)。這樣通過循環調用,直到文件的中的所有內容全被讀取。
二、登錄參數化
現在按照上面的思路,對自動化腳本中用戶、名密碼進行參數化,通過 python 文檔我們發現 python讀取文件的方式有:整個文件讀取、逐行讀取、固定字節讀取。
並沒有找到一次讀取兩條數據的好方法。
創建兩個文件,分別存放用戶名密碼。
測試腳本:
1 #coding=utf-8 2 from selenium import webdriver 3 from selenium.common.exceptions import NoSuchElementException 4 import unittest, time, os 5 class Login(unittest.TestCase): 6 def test_login(self): 7 source = open("D:\\test\\un.txt", "r") #用戶名文件 8 un = source.readline() #讀取用戶名 9 source.close() 10 source2 = open("D:\\test\\pw.txt", "r") #密碼文件 11 pw = source2.readline() #讀取密碼 12 source2.close() 13 driver=webdriver.Firefox() 14 driver.get("http://www.baidu.com/") 15 driver.maximize_window() 16 driver.find_element_by_id("txtusername").clear() 17 driver.find_element_by_id("txtusername").send_keys(un) 18 driver.find_element_by_id("txtpassword").clear() 19 driver.find_element_by_id("txtpassword").send_keys(pw) 20 driver.find_element_by_id("userlogin").click() 21 time.sleep(2) 22 try: 23 t = driver.find_element_by_xpath("//form/div[4]/div/div[1]/div[1]/div/a/img") 24 except NoSuchElementException: 25 assert 0 , u"登錄失敗,找不到左上角LOG" 26 driver.close()
Selenium+python自動化21-TXT數據參數化