自己实践成功的从csv文件中读取用户名密码并实际登录系统后判断是否登录成功,并将已经运行的用户名密码及运行结果输出到一个新的csv文件中~
1 # coding=utf-8 2 from selenium import webdriver 3 from time import sleep 4 import keyword 5 from selenium.webdriver.common.keys import Keys 6 from selenium.webdriver.support.wait import WebDriverWait 7 from selenium.webdriver.support.ui import Select 8 import csv 9 import random 10 import io 11 12 #文件路径 13 inputFilePath = "E:scriptpython-scriptcsvfile_input.csv" 14 outputFilePath = "E:scriptpython-scriptcsvfile_output.csv" 15 16 #判断成功登录后是否存在对应元素 17 def IsElementExist(driver,classname): 18 try: 19 driver.find_element_by_class_name(classname) 20 return True 21 except: 22 return False 23 #读取csv文件 24 def Readcsvfile(filePath): 25 csvFile = open(filePath, "r") 26 reader = csv.reader(csvFile) # 返回的是迭代类型 27 return reader 28 29 #将读取的内容写入一个新的csv文档 30 def Savecsvfile(filePath): 31 csvFile2 = open(filePath, 'w', newline='') # 设置newline,否则两行之间会空一行 32 writer = csv.writer(csvFile2) 33 writer.writerow(['UserName', 'Pwd','Result']) 34 writer.writerows(outputString) 35 #csvfile.close() 36 37 #主函数 38 if __name__=="__main__": 39 outputString = [] 40 lists=Readcsvfile(inputFilePath) 41 for list in lists: 42 userName=list[0] 43 pwd=list[1] 44 print(userName) 45 print(pwd) 46 driver = webdriver.Chrome() 47 driver.get("http://10.10.1.9/super/login/index.php") 48 driver.find_element_by_id("username").send_keys(list[0]) 49 sleep(1) 50 driver.find_element_by_id("password").send_keys(list[1]) 51 driver.find_element_by_id("loginbtn").click() 52 result = "Unsuccessful" 53 if IsElementExist(driver, "new_index_bottom_left_news"): 54 result = "Successful" 55 print(result) 56 outputString.append([userName, pwd,result]) 57 driver.quit() 58 Savecsvfile(outputFilePath)