跳转到主要内容

页面

页面

每个 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)