编写一段pycharm代码、Page Obiect 设计模式的详细例子
时间: 2024-05-11 13:15:16 浏览: 93
当然可以!以下是示例代码:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class LoginPage:
"""Page Object模式:登陆页面"""
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(self.driver, 10)
self.username_field = self.wait.until(EC.presence_of_element_located((By.ID, 'username')))
self.password_field = self.wait.until(EC.presence_of_element_located((By.ID, 'password')))
self.submit_button = self.wait.until(EC.element_to_be_clickable((By.ID, 'submit')))
def login(self, username, password):
self.username_field.send_keys(username)
self.password_field.send_keys(password)
self.submit_button.click()
class HomePage:
"""Page Object模式:首页"""
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(self.driver, 10)
self.greeting_text = self.wait.until(EC.presence_of_element_located((By.XPATH, '//p[contains(text(), "Welcome back, ")]')))
def get_greeting_text(self):
return self.greeting_text.text
# 使用Page Object模式进行测试
driver = webdriver.Chrome()
driver.get('http://example.com/login')
login_page = LoginPage(driver)
login_page.login('example_user', 'example_password')
home_page = HomePage(driver)
assert home_page.get_greeting_text() == 'Welcome back, example_user!'
driver.quit()
```
这段代码展示了如何使用Selenium和Page Object模式来测试一个网站的登陆和首页,以检查登陆是否正确。LoginPage和HomePage是两个独立的Page Object类,它们分别代表了登陆页面和首页,并封装了它们的元素和行为。此外,使用WebDriverWait确保了在等待元素可见性、可交互性等方面的健壮性。
阅读全文