How can I handle AJAX calls in Playwright?

Playwright is a great tool for automating browser tasks, including handling AJAX calls. AJAX (Asynchronous JavaScript and XML) is a method of exchanging data with a server and updating parts of a web page without reloading the whole page. To handle AJAX calls in Playwright, you can use the waitForResponse and waitForRequest methods.

Below are steps to handle AJAX calls:

  • Start the browser and open a new page

Python:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

JavaScript:

const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const page = await browser.newPage();
})();
  • Navigate to the website

Python:

page.goto('http://example.com')

JavaScript:

await page.goto('http://example.com');
  • Intercept AJAX calls

Playwright provides waitForResponse and waitForRequest methods that you can use to wait for an AJAX call to complete.

Python:

# Wait for a specific request
page.wait_for_request('http://example.com/api/data', timeout=5000)

# Wait for a specific response
page.wait_for_response('http://example.com/api/data', timeout=5000)

JavaScript:

// Wait for a specific request
await page.waitForRequest('http://example.com/api/data', {timeout: 5000});

// Wait for a specific response
await page.waitForResponse('http://example.com/api/data', {timeout: 5000});
  • Perform an action that triggers an AJAX call

In most cases, an AJAX call is triggered by a user action like a click event. Use the click method to simulate a click event.

Python:

page.click('#button-id')

JavaScript:

await page.click('#button-id');
  • Close the browser

Python:

browser.close()

JavaScript:

await browser.close();

Remember to replace 'http://example.com' and '#button-id' with your actual URL and element selector.

These are the basic steps to handle AJAX calls in Playwright. Depending on the specific AJAX call and the website, you may need to adjust these steps accordingly.

Related Questions

Get Started Now

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