代码之家  ›  专栏  ›  技术社区  ›  Dean Movy

Selenium和Python:将WebElement定义为属性的正确方法是什么

  •  1
  • Dean Movy  · 技术社区  · 6 年前

    浏览器

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.action_chains import ActionChains as actions
    
    
    class Browser:
    
    driver = webdriver.Chrome("C:\\chromedriver.exe")
    webDriverWait = WebDriverWait(driver, 60)
    action = actions(driver)
    
    def goto(self, url):
        Browser.driver.maximize_window()
        Browser.driver.get(url)
    

    主页

    from seleniumbase.Browser import Browser
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as ec
    from seleniumbase.BaseActions import BaseActions
    
    
    class HomePage:
        url = "myURL"
    
        def __init__(self):
            self.usernametextbox = Browser.webDriverWait.until(ec.visibility_of_element_located((By.ID, "login_email")))
            self.passwordtextbox = Browser.webDriverWait.until(
                ec.visibility_of_element_located((By.CSS_SELECTOR, "tr[id=mockpass] input")))
            self.loginbutton = Browser.webDriverWait.until(ec.element_to_be_clickable((By.NAME, "login")))
    
        def getusernametextbox(self):
            return self.usernametextbox
    
        def getpasswordtextbox(self):
            return self.passwordtextbox
    
        def getloginbutton(self):
            return self.loginbutton
    
        def login(self):
            self.getusernametextbox().send_keys("myuser@gmail.com")
            self.getpasswordtextbox().send_keys("12345678")
            self.getloginbutton().click()
    

    如你所见,我定义了我的 WebElements

    这是写的方法还是有更好的方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andersson    6 年前

    不要定义内部的每个元素 __init__ ,请尝试使用以下内容:

    @property
    def getusernametextbox(self):
        return Browser.webDriverWait.until(ec.visibility_of_element_located((By.ID, "login_email")))
    
    @property
    def getpasswordtextbox(self):
        return Browser.webDriverWait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, "tr[id=mockpass] input")))
    
    @property
    def getloginbutton(self):
        return Browser.webDriverWait.until(ec.element_to_be_clickable((By.NAME, "login")))
    
    def login(self):
            self.getusernametextbox.send_keys("myuser@gmail.com")
            self.getpasswordtextbox.send_keys("12345678")
            self.getloginbutton.click()