Python使用PageObject实现登录的代码
时间: 2024-06-10 22:06:43 浏览: 6
很高兴回答您的问题。以下是Python使用PageObject实现登录的示例代码:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginPage():
def __init__(self, driver):
self.driver = driver
self.username_input = (By.ID, 'username')
self.password_input = (By.ID, 'password')
self.login_button = (By.ID, 'login-button')
def enter_username(self, username):
username_input = self.driver.find_element(*self.username_input)
username_input.clear()
username_input.send_keys(username)
def enter_password(self, password):
password_input = self.driver.find_element(*self.password_input)
password_input.clear()
password_input.send_keys(password)
def click_login_button(self):
login_button = self.driver.find_element(*self.login_button)
login_button.click()
class TestLogin():
def setup_method(self, method):
self.driver = webdriver.Chrome()
self.driver.get('https://www.example.com/login')
def teardown_method(self, method):
self.driver.quit()
def test_login(self):
login_page = LoginPage(self.driver)
login_page.enter_username('username')
login_page.enter_password('password')
login_page.click_login_button()
WebDriverWait(self.driver, 10).until(
EC.url_contains('dashboard')
)
```
如您所看到的,该代码使用了Page Object模式,将登录页面封装成了一个类,包含了输入用户名和密码、点击登录按钮等操作。在测试脚本中,我们将页面对象实例化并调用相应的方法来完成登录操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)