实例:登录51job
part1:线性化编程
import...
#登陆51job
dr = webdriver.Chrome()
dr.implicitly_wait(20)
dr.get("https://www.51job.com/")
dr.maximize_window()
sleep(1)
#进入登陆页面
dr.find_element(By.LINK_TEXT,"登录").click()
sleep(2)
#登录系统
dr.find_element(By.CSS_SELECTOR,"#loginname.ef").send_keys("****")
sleep(0.5)
dr.find_element(By.CSS_SELECTOR,"#password").click()
dr.find_element(By.CSS_SELECTOR,"#password").send_keys("****")
sleep(0.5)
dr.find_element(By.ID,"login_btn").click()
sleep(1)
#断言
actualResult = dr.find_element(By.CSS_SELECTOR,"#resumeurl").text
if actualResult =="编辑简历":
print("pass")
else:
print("fail")
#退出系统
elem1 = dr.find_element(By.CSS_SELECTOR,".uname.e_icon.at")
elem2 = dr.find_element(By.CSS_SELECTOR,".e6.e_icon.last")
sleep(1)
Action1 = ActionChains(dr).move_to_element(elem1).perform()
sleep(1)
Action2 = ActionChains(dr).move_to_element(elem2).click().perform()
#关闭浏览器
dr.quit()
part2:二次封装
import...
from seleniumimport webdriver
from selenium.webdriver.common.byimport By
from selenium.webdriver.common.action_chainsimport ActionChains
from timeimport sleep
#基础页面
dr = webdriver.Chrome()
dr.implicitly_wait(20)
#打开被测系统
dr.get("https://www.51job.com/")
dr.maximize_window()
sleep(1)
#封装元素查找的方法
def find_elemnt(*loc):
return dr.find_element(*loc)
#页面的操作元素
#定位器:确定定位方式
#首页登录按钮
loginPage_loc = (By.LINK_TEXT,"登录")
userName_loc = (By.CSS_SELECTOR,"#loginname.ef")
passWord_loc = (By.CSS_SELECTOR,"#password")
loginBtn_loc = (By.ID,"login_btn")
assertText_loc = (By.CSS_SELECTOR,"#resumeurl")
logoutBtn_loc1 = (By.CSS_SELECTOR,".uname.e_icon.at")
logoutBtn_loc2 = (By.CSS_SELECTOR,".e6.e_icon.last")
#进入登录页面
def click_loginPage(*loginPage_loc):
find_elemnt(*loginPage_loc).click()
#输入用户名
def input_userNam(*userName_loc):
find_elemnt(*userName_loc).send_keys("****")
#输入密码
def input_passWord(*passWord_loc):
find_elemnt(*passWord_loc).send_keys("****")
#点击登录
def click_loginBtn(*loginBtn_loc):
find_elemnt(*loginBtn_loc).click()
#获取断言信息
def getAssertText(*assertText_loc):
find_elemnt(*assertText_loc).text
#退出系统
def logOutSys(*logoutBtn_loc1):
find_elemnt(*logoutBtn1_loc)
def logoutBtn(logOutSys,*logoutBtn2_loc):
self.elm2 = find_elemnt(*logoutBtn2_loc)
self.action1 = ActionChains(dr).move_to_element(self.elem1).perform()
self.action2 = ActionChains(dr).move_to_element(self.elem2).click().perform()
#测试用例
if __name__=="__main__":
click_loginPage(*loginPage_loc)
input_userNam(*userName_loc)
sleep(0.5)
input_passWord(*passWord_loc)
sleep(0.5)
click_loginBtn(*loginBtn_loc)
sleep(1)
#断言
if getAssertText(*assertText_loc) =="编辑简历":
print("pass")
else:
print("fail")
#退出
logoutBtn(logOutSys,*logoutBtn2_loc)
sleep(1)
dr.quit()