• object设计模式.py


    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from time import sleep
    #创建page类:
    class Page(object):
    """
    基础类、用于页面对象类的继承
    """
    login_url = "http://www.126.com"
    def __init__(self,selenium_driver,base_url = login_url):
    """
    首先创建一个基础类Page,在初始化方法init)中定义驱动(driver)、基本的URL
    (base_url)和超时时间(timeout)等。
    :param selenium_driver:
    :param base_url:
    """
    self.base_url = base_url
    self.driver = selenium_driver
    self.timeout = 30

    def on_page(self):
    return self.driver.current_url == (self.base_url + self.url)

    def _open(self,url):
    url = self.base_url + url
    self.driver.get(url)
    assert self.on_page(),"Did not land on %s" %url

    def open(self):
    self._open(self.url)

    def find_element(self,*loc):
    return self.driver.find_element(*loc)

    """
    定义open)方法用于打开URL网站,但它本身并未做这件事情,而是交由_open)方法来实现。关于URL地址的断言部分,则交由on page()方法来实现,而find_element)方法用于元素的定位。
    """

    #创建LoginPage类:
    class LoginPage(Page):
    """
    126邮箱登录页面模型
    LoginPage类中主要对登录页面上的元素进行封装,使其成为更具体的操作方法。例如,用户名、密码和登录按钮都被封装成了方法。
    """
    url = "/"
    #定位器
    username_loc = (By.ID,"idInput")
    password_loc = (By.ID,"pwdInput")
    submit_loc = (By.ID,"loginBtn")
    #Action
    def type_username(self,username):
    self.find_element(*self.username_loc).send_keys(username)

    def type_password(self,password):
    self.find_element(*self.password_loc).send_keys(password)

    def submit(self):
    self.find_element(*self.submit_loc).click()

    def test_user_login(driver,username,password):
    """
    测试获取的用户名/密码是否可以登录
    test_user_login)函数将单个的元素操作组成一个完整的动作,而这个动作包含了打开浏览器、输入用户名/密码、点击登录等单步操作。在使用该函数时需要将driver、username、password等信息作为函数的入参,这样该函数具有很强的可重用性。
    :param driver:
    :param username:
    :param password:
    :return:
    """
    login_page = LoginPage(driver)
    login_page.open()
    login_page.type_username(username)
    login_page.type_password(password)
    login_page.submit()

    def main():
    try:
    driver = webdriver.Firefox()
    username = "username"
    password = "123456"
    test_user_login(driver,username,password)
    sleep(3)
    text = driver.find_element_by_xpath("//span[@id='spnUid']").text
    assert (text == "username@126.com") #用户名称不匹配、登录失败!
    finally:
    #关闭浏览器窗口:
    driver.close()

    if __name__ == '__main__':
    main()
  • 相关阅读:
    Trapping Rain Water
    Construct Binary Tree from Preorder and Inorder Traversal
    Flatten Binary Tree to Linked List
    Permutations II
    Unique Paths II
    Path Sum II
    Unique Binary Search Trees II
    evdev module-----uinput.py
    evdev module-----events.py
    evdev module-----device.py
  • 原文地址:https://www.cnblogs.com/zhang-da/p/12210535.html
Copyright © 2020-2023  润新知