跳到主要內容

頁面

頁面

每個 BrowserContext 可以有多個頁面。Page 指的是瀏覽器環境中的單一分頁或彈出視窗。它應該用於導航到 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

處理新頁面

瀏覽器環境上的 page 事件可以用於取得在環境中建立的新頁面。這可以用於處理由 target="_blank" 連結開啟的新頁面。

# 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

# Interact with the new page normally
new_page.get_by_role("button").click()
print(new_page.title())

如果觸發新頁面的動作未知,可以使用以下模式。

# Get all new pages (including popups) in the context
def handle_page(page):
page.wait_for_load_state()
print(page.title())

context.on("page", handle_page)

處理彈出視窗

如果頁面開啟彈出視窗(例如由 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

# Interact with the popup normally
popup.get_by_role("button").click()
print(popup.title())

如果觸發彈出視窗的動作未知,可以使用以下模式。

# Get all popups when they open
def handle_popup(popup):
popup.wait_for_load_state()
print(popup.title())

page.on("popup", handle_popup)