[英]Create a base driver class and inherit webdriver
在 Python/Selenium 中,我主要嘗試創建一個瀏覽器類,以便我可以創建自定義函數,例如 click 或 type 等,並通過鍵入一些簡單的東西browser.click(element)
例如browser.click(element)
或browser.type_text(element, text)
browser.click(element)
來輕松調用這些函數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)
正如@Guy 所提到的,您混淆了WebDriver
類和WebElement
類的功能。 WebDriver
類確實具有用於 URL 導航的get
方法,但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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.