How do I handle page redirects in Playwright?

Playwright is a powerful tool for end-to-end testing of web apps, it provides you with APIs to handle various browser contexts including page redirection.

Handling page redirects in Playwright can be achieved in several ways, depending on the context of the situation. I will show you how to handle page redirects in both Python and JavaScript.

Python

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    # Listen for all Page.Events.Response events and print to stdout
    def handle_response(response):
        print('Redirected to:', response.url)
    page.on("response", handle_response)
    page.goto('http://example.com')  # replace with your url
    browser.close()

with sync_playwright() as p:
    run(p)

In the above example, we are listening for the response events and printing the URL of the redirected page.

JavaScript

const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // Listen for all page.Response events and print to stdout
  page.on('response', response => {
    console.log('Redirected to:', response.url());
  });
  await page.goto('http://example.com'); // replace with your url

  await browser.close();
})();

In the JavaScript example, we are doing the same thing as in Python. We are listening to the response event and then logging the URL of the redirected page.

You can also handle redirects by checking the status code of the response. A 3xx status code usually indicates a redirect. For example, 301 and 302 are common status codes for redirects.

Please note that the page.goto() function will follow redirects by default and only resolve when the final page is loaded. Therefore, if you simply want to follow the redirect without any special handling, no additional code is required.

Remember to replace 'http://example.com' with the URL that you want to handle redirects for.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon