Evaluating JavaScript expressions using Playwright can be done via the evaluate()
method provided by the API. The evaluate()
function allows you to execute JavaScript in the context of the browser, making it an essential tool for dealing with dynamic content that requires JavaScript to display.
Here's how you can use it in Python and JavaScript.
Python
In Python, Playwright provides a good API to evaluate JavaScript expressions. Here is a simple example:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
result = page.evaluate("() => document.title")
print(result)
browser.close()
In this example, page.evaluate()
is used to execute JavaScript in the context of the page. Specifically, it is getting the title of the page.
JavaScript
Similarly, in JavaScript, you can use the evaluate()
method to execute JavaScript expressions:
const playwright = require('playwright');
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
const result = await page.evaluate(() => document.title);
console.log(result);
await browser.close();
})();
In this example as well, page.evaluate()
is used to execute a JavaScript function in the context of the page. It is getting the title of the webpage by using document.title
.
Please note that the evaluate()
method can only be used to execute serializable data, so non-serializable objects like DOM elements cannot be returned. For this, Playwright provides the evaluateHandle()
method.
Moreover, the evaluate()
method can also accept arguments that get passed to the evaluated function. Here is an example:
const playwright = require('playwright');
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
const selector = 'body';
const backgroundColor = await page.evaluate((selector) => {
return getComputedStyle(document.querySelector(selector)).backgroundColor;
}, selector);
console.log(backgroundColor); // Will log the background color of the body element
await browser.close();
})();
In this example, the evaluate()
method is used with an argument, the CSS selector of the element to check. The evaluated function gets the background color of the selected element.