8-8(selenium- 登陆案例)

2019-08-26  本文已影响0人  不知名的二狗

login.html

<!DOCTYPE html>
<html>
<title>登陆页面</title>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
账号:
<input type = text name = "user"  />
密码:
<input type = password name = "password"  />
<button type = submit  id = tijiao ><a href="index.html">登陆</a></button>
</body>
</html>

login.py

import os
import time
def login(driver,user,pwd):
    driver.get('file:///'+os.path.abspath('login.html'))
    time.sleep(3)
    driver.find_element_by_name("user").send_keys(user)
    driver.find_element_by_name("password").send_keys(pwd)
    driver.find_element_by_id("tijiao").click()
      driver.close()
    driver.quit()
if __name__ == "__main__":
    unittest.main()

test_class.py

from selenium import webdriver
import unittest
from ke7_unitest.login import login
class LoginCase(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
    def test_login1(self):
        login(self.driver,"user","123")

优化之后

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
import os
class Base():
    def __init__(self,driver):
        self.driver = driver
        self.timeout = 10
        self.t = 0.5
     # 定位一个
    def findElement(self,locator):
        ele = WebDriverWait(self.driver, self.timeout, self.t).until(lambda x: x.find_element(*locator))
        return ele

    # 定位一组
    def findElements(self, locator):
        eles = WebDriverWait(self.driver, self.timeout, self.t).until(lambda x: x.find_elements(*locator))
        return eles
    def sendKeys(self,locator,text):
        ele = self.findElement(locator)
        ele.send_keys(text)
    def click(self,locator):
        ele = self.findElement(locator)
        ele.click()

if __name__ == "__main__":
    driver = webdriver.Chrome()
    driver.get("file:///"+os.path.abspath("login.html"))
    login = Base(driver)
    # 通过By的方式定位
    # loc1 = (By.NAME, 'user')
    # loc2 = (By.NAME, 'password')
    # loc3 = (By.ID, 'tijiao')
    loc1 = ("name","user")
    loc2 = ("name","password")
    loc3 = ("id","tijiao")
    login.sendKeys(loc1,"user")
    login.sendKeys(loc2,"password")
    login.click(loc3)
    driver.close()
    driver.quit()
上一篇下一篇

猜你喜欢

热点阅读