首页 > 解决方案 > 创建基驱动类并继承webdriver

问题描述

在 Python/Selenium 中,我主要尝试创建一个浏览器类,以便我可以创建自定义函数,如单击或键入等,并通过键入简单的内容(如browser.click(element)或)轻松调用这些函数browser.type_text(element, text)

我认为我走在了正确的轨道上,但我无法让继承发挥作用。例如,当我创建一个浏览器实例browser = Browser()并尝试使用 webdriver 的正常功能时browser.get(webpage),我收到一条错误消息,指出没有 GET 功能。我在正确的轨道上吗?有没有更好的办法?

class Browser(webdriver.Chrome):
    def __init__():
        super(self).init()
        self.browser = webdriver.Chrome()

    def click(element):
        WebDriverWait(self, 10).until(EC.element_to_be_clickable(element)).click()

browser = Browser()
element = (By.ID, elements['remember'])
browser.click(element)

更新: 所以看起来我能够弄清楚我最初打算做什么。

我想使用一个类创建一个 webdriver,并基本上扩展该库以包含一些自定义函数。我会解释的。

class Browser(webdriver.Chrome):
    def __init__(self):
        super().__init__()

    def click(self, element):
        WebDriverWait(self, 10).until(EC.element_to_be_clickable(element)).click()

    def type(self, element, text):
        for i in text:
            WebDriverWait(browser, 10).until(EC.visibility_of_element_located(element)).send_keys(i)
            time.sleep(random.uniform(0.05,0.25))

所以基本上在这里我只是添加了一个自定义的单击和键入功能,以使 webdriver 更方便地等待一个元素并单击或键入等。

browser = Browser()
browser.click(element)
browser.type(element, text)

标签: pythonpython-3.xseleniumselenium-webdriverselenium-chromedriver

解决方案


正如@Guy 所提到的,您混淆了WebDriver类和WebElement类的功能。该类WebDriver确实具有getURL 导航等方法,但WebElement该类具有 等方法click。我不使用您当前的方法,而是推荐一种在 Selenium 中流行的设计模式:页面对象模型设计模式

遵循此设计模式将允许您轻松调用更简单的方法名称。例如,直接取自链接页面:

from element import BasePageElement
from locators import MainPageLocators

class SearchTextElement(BasePageElement):
    """This class gets the search text from the specified locator"""

    #The locator for search box where search string is entered
    locator = 'q'


class BasePage(object):
    """Base class to initialize the base page that will be called from all pages"""

    def __init__(self, driver):
        self.driver = driver


class MainPage(BasePage):
    """Home page action methods come here. I.e. Python.org"""

    #Declares a variable that will contain the retrieved text
    search_text_element = SearchTextElement()

    def is_title_matches(self):
        """Verifies that the hardcoded text "Python" appears in page title"""
        return "Python" in self.driver.title

    def click_go_button(self):
        """Triggers the search"""
        element = self.driver.find_element(*MainPageLocators.GO_BUTTON)
        element.click()


class SearchResultsPage(BasePage):
    """Search results page action methods come here"""

    def is_results_found(self):
        # Probably should search for this text in the specific page
        # element, but as for now it works fine
        return "No results found." not in self.driver.page_source

这将允许您进行简单命名的方法调用:

MainPage.click_go_button()

推荐阅读