代码如下:
from selenium import webdriver import time from log_module import Loginfo from userdata import get_webinfo,get_userinfo def openBrower(): webdriver_handle = webdriver.Firefox() return webdriver_handle def openUrl(handle,url): handle.get(url) def findElement(d,arg): ele_login = d.find_element_by_link_text(arg['login_text']) ele_login.click() time.sleep(5) userEle = d.find_element_by_name(arg['userid']) pwdEle = d.find_element_by_name(arg['pwdid']) loginEle = d.find_element_by_css_selector('input[type="button"]') return userEle,pwdEle,loginEle def sendVals(eletuple,arg): listkey = ['uname','pwd'] i = 0 for key in listkey: eletuple[i].clear() eletuple[i].send_keys(arg[key]) i+=1 eletuple[2].click() def checkResult(d,xpath1,arg,log): try: err = d.find_element_by_xpath(xpath1) print("Account and Pwd Error!") msg = '%s %s:error:%s'%(arg['uname'],arg['pwd'],err.text) log.log_write(msg) except: print("Account and Pwd Right!") msg = '%s %s:pass' % (arg['uname'],arg['pwd']) log.log_write(msg) def login_test(ele_dict,user_list): d = openBrower() log = Loginfo() openUrl(d,ele_dict['url']) ele_tuple = findElement(d,ele_dict) for arg in user_list: sendVals(ele_tuple, arg) checkResult(d,ele_dict['errorid'],arg,log) log.close() # 当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行 if __name__ == '__main__': ele_dict = get_webinfo(r'G:yayapycharmwebinfo') user_list = get_userinfo(r'G:yayapycharmuserinfo') login_test(ele_dict,user_list)
webinfo
url = https://www.imooc.com/ login_text = 登录 userid = email pwdid = password errorid=/html/body/div[9]/div[2]/div/form/div[1]/p
userinfo
uname=1 pwd=1
userdata.py
def get_webinfo(path): web_info = {} config = open(path,encoding='UTF-8') for line in config: result = [ele.strip() for ele in line.split('=')] web_info.update(dict([result])) return web_info def get_userinfo(path): user_info = [] config = open(path,encoding='UTF-8') for line in config: user_dict = {} result = [ele.strip() for ele in line.split(' ')] for r in result: account = [ele.strip() for ele in r.split('=')] user_dict.update(dict([account])) user_info.append(user_dict) return user_info if __name__ == '__main__': webinfo = get_webinfo(r'G:yayapycharmwebinfo') for key in webinfo: print(key,webinfo[key]) userinfo = get_userinfo(r'G:yayapycharmuserinfo') for l in userinfo: print(l)
log_moudle.py
import time class Loginfo(object): def __init__(self,path='',mode='w'): fname = path+time.strftime('%Y-%m-%d',time.gmtime()) self.log = open(path+fname+'.txt',mode,encoding='UTF-8') def log_write(self,msg): self.log.write(msg) def close(self): self.log.close() if __name__ == '__main__': log = Loginfo() log.log_write('Test Loginfo 测试') log.close()
生成log如下:
1 1:error:请输入正确的邮箱或手机号