playwright支持PO模式
创建页面对象
class SearchPage:
def __init__(self, page):
self.page = page
self.search_term_input = page.get_by_role("searchbox", name="输入搜索词")
def navigate(self):
self.page.goto("https://bing.com")
def search(self, text):
self.search_term_input.fill(text)
self.search_term_input.press("Enter")
编写测试用例
from playwright.sync_api import sync_playwright
from search import SearchPage
# in the test
def test_demo(playwright):
browser = playwright.chromium.launch
page = browser.new_page()
search_page = SearchPage(page)
search_page.navigate()
search_page.search("search query")
with sync_playwright() as playwright:
test_demo(playwright)
页面
每个浏览器上下文可以有多个页面。页面是指浏览器上下文中的单个选项卡或弹出窗口。它应该用于导航到 URL 并与页面内容交互。
单个页面
- 同步
-
page = context.new_page() # Navigate explicitly, similar to entering a URL in the browser. page.goto('http://example.com') # Fill an input. page.locator('#search').fill('query') # Navigate implicitly by clicking a link. page.locator('#submit').click() # Expect a new url. print(page.url)
多个页面
每个浏览器上下文可以托管多个页面(选项卡)。
- 每个页面的行为都像一个专注的活动页面。不需要将页面置于最前面。
- 上下文中的页面遵循上下文级仿真,例如视口大小、自定义网络路由或浏览器区域设置。
- 同步
# create two pages
page_one = context.new_page()
page_two = context.new_page()
# get pages of a browser context
all_pages = context.pages
处理新页面
浏览器上下文中的事件可用于获取在上下文中创建的新页面。这可用于处理由链接打开的新页面。
- 同步
# Get page after a specific action (e.g. clicking a link)
with context.expect_page() as new_page_info:
page.get_by_text("open new tab").click() # Opens a new tab
new_page = new_page_info.value
new_page.wait_for_load_state()
print(new_page.title())
处理弹出窗口
如果页面打开弹出窗口(例如.pages通过链接打开),您可以通过收听页面上的事件来获取对它的引用。target="_blank"
popup
除了事件之外,还会发出此事件,但仅适用于与此页面相关的弹出窗口。browserContext.on('page')
- 同步
# Get popup after a specific action (e.g., click)
with page.expect_popup() as popup_info:
page.get_by_text("open the popup").click()
popup = popup_info.value
popup.wait_for_load_state()
print(popup.title())