Playwright
Playwright is a cross-browser library written by Microsoft to aide in cross-browser testing and development. This page helps you get started quickly connecting remotely to Browserless instead of launching browsers locally. You can find more detailed documentation on playwright's documentation site.
We (officially) support Playwright in several languages, as well as using Playwright with an unlocked endpoint via our BrowserQL.
To avoid errors with no apparent reason, please make sure your playwright version is compatible with one of these versions.
- Javascript
- Python
- Java
- C#
We support playwright
for Javascript out of the box for all their supported browsers.
Using the Playwright Protocol
The standard connect
method uses Playwright's built-in browser-server protocol to handle the connection. This, generally, is a faster and more fully-featured method since it supports most of the Playwright parameters (such as using a proxy and more). However, since this requires the usage of Playwright in our servers, your client's Playwright version should match ours.
Take a screenshot in Playwright with Firefox
import playwright from "playwright-core";
const pwEndpoint = `wss://production-sfo.browserless.io/firefox/playwright?token=YOUR_API_TOKEN_HERE`;
const browser = await playwright.firefox.connect(pwEndpoint);
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("https://www.nexcess.net/web-tools/browser-information/");
await new Promise((resolve) => setTimeout(resolve, 50000));
await page.screenshot({
path: `firefox.png`,
});
await browser.close();
Similarly, if you need to use another browser, just make sure the Playwright Browser object matches the endpoint.
Using the Chrome DevTools Protocol
The connectOverCDP
method allows Playwright to connect through Chrome's DevTools Protocol. While this is more functionally similar to how puppeteer
operates, it does come with a slight performance hit since sessions are more "chatty" over the network versus Playwright's connect
. Furthermore, you can only use the Chrome for these connections.
Take a screenshot in Playwright
import playwright from "playwright";
const browser = await playwright.chromium.connectOverCDP(
"wss://production-sfo.browserless.io?token=YOUR_API_TOKEN_HERE"
);
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("https://www.example.com/");
await page.screenshot({ path: "cdp.png" });
await browser.close();
Using 3rd Party Proxies with Playwright
When using Playwright with browserless, you can set up a 3rd party proxy by providing proxy configuration to the newContext()
method. This is different from how proxies are handled in Puppeteer, as Playwright allows you to specify proxy settings directly at the context level:
import playwright from "playwright-core";
const browser = await playwright.chromium.connectOverCDP(
"wss://production-sfo.browserless.io?token=YOUR_API_TOKEN_HERE"
);
const context = await browser.newContext({
proxy: {
server: "http://domain:port",
username: "username",
password: "password",
},
});
const page = await context.newPage();
await page.goto("https://icanhazip.com/");
console.log(await page.content());
await browser.close();
This approach applies the proxy configuration at the context level, which means all pages created from that context will use the specified proxy. For more detailed information about using proxies with Playwright, see our Third Party Proxies documentation.
Code Snippet
Below is a copy-paste example (remember to replace the API token with yours!) that should be a great starting point since it shows how to use Playwright's methods with file saving capabilities:
import pw from "playwright-core";
import fs from "fs";
async function main() {
let browser = null;
try {
const url = "https://www.example.com";
const token = "YOUR_API_TOKEN_HERE";
const launchArgs = JSON.stringify({
args: [`--window-size=1920,1080`],
headless: false,
stealth: true,
timeout: 30000
});
console.log("Connecting to browser...");
browser = await pw.chromium.connect(
`wss://production-sfo.browserless.io/chromium/playwright?token=${token}&launch=${launchArgs}`
);
console.log("Creating new page...");
const context = await browser.newContext({
viewport: { width: 1920, height: 1080 },
userAgent: 'My Custom User Agent/1.0'
});
const page = await context.newPage();
console.log("Navigating to example.com...");
await page.goto(url);
const title = await page.title();
console.log(`The page's title is: ${title}`);
const html = await page.content();
fs.writeFileSync("example.html", html);
console.log(`HTML file saved.`);
await page.screenshot({ path: "example.png" });
console.log(`Screenshot saved.`);
const pdfBuffer = await page.pdf({ format: "A4" });
fs.writeFileSync("example.pdf", pdfBuffer);
console.log(`PDF file saved.`);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
if (browser) {
try {
console.log("Closing browser...");
await browser.close();
} catch (closeError) {
console.error("Error while closing browser:", closeError.message);
}
}
}
}
main().catch(error => {
console.error("Unhandled error in main function:", error);
});
We support Playwright for Python out of the box via their playwright.browser.connect()
method.
Here's a simple snippet of its implementation, we can add additional features through the context, such as a proxy if necessary.
Print page content
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.firefox.connect('wss://production-sfo.browserless.io/firefox/playwright?token=YOUR_API_TOKEN_HERE')
context = browser.new_context()
page = context.new_page()
page.goto('http://www.example.com', wait_until='domcontentloaded')
print(page.content())
context.close()
Code Snippet
Below is a copy-paste example (remember to replace the API token with yours!) that should be a great starting point since it shows how to use Playwright's methods with file saving capabilities:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.connect(
'wss://production-sfo.browserless.io/chromium/playwright?token=YOUR_API_TOKEN_HERE'
)
context = browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent='My Custom User Agent/1.0'
)
page = context.new_page()
print("Navigating to example.com...")
page.goto("https://www.example.com", wait_until="domcontentloaded")
title = page.title()
print(f"The page's title is: {title}")
html = page.content()
with open("example.html", "w") as f:
f.write(html)
print("HTML file saved.")
page.screenshot(path="example.png")
print("Screenshot saved.")
pdf_buffer = page.pdf(format="A4")
with open("example.pdf", "wb") as f:
f.write(pdf_buffer)
print("PDF file saved.")
browser.close()
We support playwright
for Java out of the box, and just as with JavaScript, we can use either connect()
or connectOverCDP()
.
Here's a simple snippet of its implementation.
Scrape a site title with playwright
package org.example;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
String wsEndpoint = "ws://production-sfo.browserless.io/webkit/playwright?token=YOUR_API_TOKEN_HERE";
Browser browser = playwright.webkit().connect(wsEndpoint);
Page page = browser.newPage();
page.navigate("https://www.whatismybrowser.com/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("webkit.png")));
browser.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
We support playwright
for C# out of the box, and just as with JavaScript, we can use either connect()
or connectOverCDP()
.
Take a screenshot in playwright
using Microsoft.Playwright;
using System.Threading.Tasks;
using System;
class Program
{
public static async Task Main()
{
try{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.ConnectOverCDPAsync("wss://production-sfo.browserless.io?token=YOUR_API_TOKEN_HERE");
var page = await browser.NewPageAsync();
await page.GotoAsync("https://example.com/", new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle });
await page.ScreenshotAsync(new PageScreenshotOptions { Path = "example.png" });
}
catch (Exception e){
Debug.WriteLine(e.ToString());
}
}
}