To work with many tabs in Playwright with Python, utilize the Page.contexts property to retrieve a list of browser contexts and then loop over each context to access the individual pages.
Example
from playwright.sync_api import sync_playwright
def handle_multiple_tabs():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page1 = context.new_page()
page1.goto('https://www.programsbuzz.com/user/login')
print("Page 1 URL:", page1.url)
page2 = context.new_page()
page2.goto('https://www.programsbuzz.com')
print("Page 2 URL:", page2.url)
context.pages[0].bring_to_front()
print("Switched to Page 1")
page1.wait_for_load_state()
page1.locator('#edit-name').type('Monkey D Luffy')
context.pages[1].bring_to_front()
print("Switched to Page 2")
page2.locator('.fas.fa-search').click()
browser.close()
handle_multiple_tabs()
- We use playwright.chromium.launch() to launch the browser and browser.new_context() to generate a new browser context.
- We then use context.new_page() to create two tabs within the context and Page.goto() to navigate to distinct websites.
- To transition between tabs, we use the context.pages list, which contains all of the context's open pages.
- Individual pages in the list can be accessed by their index. Context.pages[0] represents the first tab, whereas context.pages[1] describes the second.
- By referencing the various page objects (page 1, page 2, etc.) and using Playwright's APIs, you may conduct operations on each Page, such as clicking items, filling forms, or extracting data.
- Log in to post comments