playwright supports PO mode
create page object
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")
Write test cases
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)
page
Each browser context can have multiple pages. A page refers to a single tab or pop-up window within the context of a browser. It should be used to navigate to URLs and interact with page content.
single page
- Synchronize
-
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)
multiple pages
Each browser context can host multiple pages (tabs).
- Each page behaves like a focused active page. There is no need to bring the page to the front.
- Pages in context obey context-level emulations such as viewport size, custom network routing, or browser locale.
- Synchronize
# create two pages
page_one = context.new_page()
page_two = context.new_page()
# get pages of a browser context
all_pages = context.pages
process new page
Events in the browser context can be used to get new pages created in the context. This can be used to handle new pages opened by links.
- Synchronize
# 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())
Handle popups
If the page opens the popup (e.g. .pages opened via a link), you can get a reference to it by listening to events on the page.target="_blank"
popup
This event is emitted in addition to events, but only for popups associated with this page.browserContext.on('page')
- Synchronize
# 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())