自动化测试怎么用PO封装测试将网页的文本信息提取并输出
时间: 2023-08-16 19:05:05 浏览: 49
使用PO模式(Page Object 模式)的自动化测试可以将页面抽象为一个个页面对象,每个页面对象都有自己的属性和方法,方便测试用例的编写和维护。
以下是一个使用Python语言的示例代码,可以使用Selenium和BeautifulSoup库,封装一个获取网页文本信息的测试用例。
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
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.CLASS_NAME, 'btn-login')
def login(self, username, password):
self.driver.get('http://www.example.com/login')
WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.username_input))
self.driver.find_element(*self.username_input).send_keys(username)
self.driver.find_element(*self.password_input).send_keys(password)
self.driver.find_element(*self.login_button).click()
class HomePage:
def __init__(self, driver):
self.driver = driver
self.welcome_text = (By.CLASS_NAME, 'welcome-text')
def get_welcome_text(self):
WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.welcome_text))
soup = BeautifulSoup(self.driver.page_source, 'html.parser')
return soup.find('div', {'class': 'welcome-text'}).text
if __name__ == '__main__':
driver = webdriver.Chrome()
try:
login_page = LoginPage(driver)
login_page.login('username', 'password')
home_page = HomePage(driver)
welcome_text = home_page.get_welcome_text()
print(welcome_text)
finally:
driver.quit()
```
在上述代码中,LoginPage是一个页面对象,封装了登录页面的元素定位和登录操作。HomePage也是一个页面对象,封装了主页面的元素定位和获取欢迎文本信息的方法。在HomePage的get_welcome_text方法中,使用BeautifulSoup库解析网页源代码,找到欢迎文本的div标签,并返回其中的文本信息。最后,在主程序中实例化LoginPage和HomePage对象,调用相应的方法获取欢迎文本信息并输出。