### Basic Playwright Rust Browser Automation Example Source: https://github.com/octaltree/playwright-rust/blob/master/README.md This is a fundamental example demonstrating how to initialize Playwright, launch a headless Chromium browser, create a new page, navigate to a URL, execute JavaScript to get the current URL, and click an element. It utilizes the tokio runtime for asynchronous operations and expects successful execution, returning a Result. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; // Install browsers let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; page.goto_builder("https://example.com/").goto().await?; // Exec in browser and Deserialize with serde let s: String = page.eval("() => location.href").await?; assert_eq!(s, "https://example.com/"); page.click_builder("a").click().await?; Ok(()) } ``` -------------------------------- ### Device Emulation with Playwright Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt Emulates mobile devices and custom viewport configurations using Playwright in Rust. This example utilizes the 'playwright' and 'tokio' crates. It demonstrates how to get predefined device settings, apply them to a browser context, and inspect the resulting viewport size. It also shows how to list all available device definitions. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; // Get predefined device let iphone = playwright.device("iPhone 12").unwrap(); // Create context with device settings let context = browser.context_builder() .set_device(&iphone) .build() .await?; let page = context.new_page().await?; page.goto_builder("https://example.com/").goto().await?; // Check viewport let viewport = page.viewport_size()?; println!("Viewport: {:?}", viewport); // List all available devices let devices = playwright.devices(); for device in devices.iter().take(5) { println!("Device: {}", device.name); } browser.close().await?; Ok(()) } ``` -------------------------------- ### Launch Browser and Create Context (Rust) Source: https://context7.com/octaltree/playwright-rust/llms.txt This example shows how to launch a browser instance (e.g., Chromium) and create an isolated browsing context with custom viewport and user agent settings using Playwright for Rust. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; // Launch browser let chromium = playwright.chromium(); let browser = chromium .launcher() .headless(true) .launch() .await?; // Create isolated browser context (incognito mode) let context = browser .context_builder() .viewport(Some(playwright::api::Viewport { width: 1920, height: 1080, })) .user_agent(Some("Mozilla/5.0 Custom Agent")) .build() .await?; // Create new page in context let page = context.new_page().await?; // Cleanup browser.close().await?; Ok(()) } ``` -------------------------------- ### Install Playwright and Initialize Browser Driver (Rust) Source: https://context7.com/octaltree/playwright-rust/llms.txt This snippet demonstrates how to add Playwright as a dependency and initialize the browser driver using Rust. It includes installing all browsers or specific ones like Chromium. ```rust // Cargo.toml [dependencies] playwright = "0.0.20" tokio = { version = "1.9.0", features = ["full"] } // main.rs use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { // Initialize playwright and install driver let playwright = Playwright::initialize().await?; // Install all browsers (chromium, firefox, webkit) playwright.prepare()?; // Or install specific browser playwright.install_chromium()?; Ok(()) } ``` -------------------------------- ### Rust: Playwright Multiple Browser Support Source: https://context7.com/octaltree/playwright-rust/llms.txt Illustrates launching and interacting with multiple browser engines (Chromium, Firefox, WebKit) using Playwright for Rust. This example requires the 'playwright' and 'tokio' crates. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; // Launch Chromium let chromium = playwright.chromium(); let chromium_browser = chromium.launcher() .headless(true) .launch() .await?; // Launch Firefox let firefox = playwright.firefox(); let firefox_browser = firefox.launcher() .headless(true) .launch() .await?; // Launch WebKit let webkit = playwright.webkit(); let webkit_browser = webkit.launcher() .headless(true) .launch() .await?; // Use different browsers let chromium_context = chromium_browser.context_builder().build().await?; let firefox_context = firefox_browser.context_builder().build().await?; let webkit_context = webkit_browser.context_builder().build().await?; let chromium_page = chromium_context.new_page().await?; let firefox_page = firefox_context.new_page().await?; let webkit_page = webkit_context.new_page().await?; // Navigate all browsers chromium_page.goto_builder("https://example.com/").goto().await?; firefox_page.goto_builder("https://example.com/").goto().await?; webkit_page.goto_builder("https://example.com/").goto().await?; // Get browser versions println!("Chromium: {}", chromium_browser.version()?); println!("Firefox: {}", firefox_browser.version()?); println!("WebKit: {}", webkit_browser.version()?); // Cleanup chromium_browser.close().await?; firefox_browser.close().await?; webkit_browser.close().await?; Ok(()) } ``` -------------------------------- ### Install Playwright Rust Dependency Source: https://github.com/octaltree/playwright-rust/blob/master/README.md This code snippet shows how to add the Playwright Rust library as a dependency in your Cargo.toml file. It specifies the version of the playwright crate to be used in the project. ```toml [dependencies] playwright = "0.0.20" ``` -------------------------------- ### Select and Interact with Elements (Rust) Source: https://context7.com/octaltree/playwright-rust/llms.txt This Rust example showcases how to interact with web page elements using CSS selectors. It includes clicking buttons, filling input fields, querying single and multiple elements, and checking element states like visibility and enabled status. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; page.goto_builder("https://example.com/").goto().await?; // Click element page.click_builder("button#submit") .timeout(Some(5000.0)) .click() .await?; // Fill input field page.fill_builder("input[name='email']", "user@example.com") .timeout(Some(3000.0)) .fill() .await?; // Query single element if let Some(element) = page.query_selector("a.link").await? { let text = element.inner_text().await?; let href = element.get_attribute("href").await?; println!("Link: {} -> {:?}", text, href); } // Query multiple elements let links = page.query_selector_all("a").await?; println!("Found {} links", links.len()); // Check element state let is_visible = page.is_visible("div.modal", None).await?; let is_enabled = page.is_enabled("button", None).await?; println!("Modal visible: {}, Button enabled: {}", is_visible, is_enabled); browser.close().await?; Ok(()) } ``` -------------------------------- ### Navigate, Extract Content, and Get Page Info (Rust) Source: https://context7.com/octaltree/playwright-rust/llms.txt This Rust code snippet demonstrates navigating to a URL with options, retrieving the page title, current URL, full HTML content, and text content of a specific element using Playwright. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; // Navigate to URL with options page.goto_builder("https://example.com/") .timeout(Some(30000.0)) .goto() .await?; // Get page title let title = page.title().await?; println!("Title: {}", title); // Get current URL let url = page.url()?; println!("URL: {}", url); // Get full HTML content let content = page.content().await?; println!("Content length: {}", content.len()); // Get text content of element let text = page.text_content("h1", None).await?; println!("Heading: {:?}", text); browser.close().await?; Ok(()) } ``` -------------------------------- ### Advanced Browser Context Configuration in Playwright Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt Configures browser contexts with advanced settings including viewport, user agent, locale, timezone, geolocation, permissions, custom headers, HTTPS error handling, and download acceptance. This example uses the 'playwright' and 'tokio' crates and requires a running Playwright instance. It demonstrates setting and retrieving cookies, and granting permissions. ```rust use playwright::Playwright; use playwright::api::{Cookie, Geolocation, HttpCredentials}; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; // Create context with full configuration let mut extra_headers = HashMap::new(); extra_headers.insert("X-Custom-Header".to_string(), "value".to_string()); let context = browser.context_builder() .viewport(Some(playwright::api::Viewport { width: 1280, height: 720, })) .user_agent(Some("Custom UserAgent")) .locale(Some("en-US")) .timezone_id(Some("America/New_York")) .geolocation(Some(Geolocation { latitude: 40.7128, longitude: -74.0060, accuracy: Some(100.0), })) .permissions(Some(&["geolocation".to_string(), "notifications".to_string()])) .extra_http_headers(Some(extra_headers)) .ignore_https_errors(Some(true)) .accept_downloads(Some(true)) .build() .await?; let page = context.new_page().await?; // Add cookies let cookie = Cookie { name: "session".to_string(), value: "abc123".to_string(), domain: "example.com".to_string(), path: "/".to_string(), expires: -1.0, http_only: false, secure: false, same_site: Some("Lax".to_string()), }; context.add_cookies(&[cookie]).await?; // Get cookies let cookies = context.cookies(&["https://example.com".to_string()]).await?; println!("Cookies: {:?}", cookies); // Set geolocation context.set_geolocation(Some(&Geolocation { latitude: 51.5074, longitude: -0.1278, accuracy: Some(50.0), })).await?; // Grant permissions context.grant_permissions( &["camera".to_string(), "microphone".to_string()], Some("https://example.com") ).await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Evaluate JavaScript and Get Results in Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt Shows how to execute arbitrary JavaScript code within the browser context and retrieve the results using Playwright in Rust. This function requires Playwright and Tokio, and can handle simple values or complex serialized objects. It can also evaluate JavaScript on specific elements. ```rust use playwright::Playwright; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct PageInfo { title: String, url: String, width: i32, height: i32, } #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; page.goto_builder("https://example.com/").goto().await?; // Simple evaluation - get href let href: String = page.eval("() => location.href").await?; println!("Current URL: {}", href); // Evaluate with return value let scroll_height: i32 = page.eval("() => document.body.scrollHeight").await?; println!("Scroll height: {}", scroll_height); // Evaluate with argument let result: String = page.evaluate( "(text) => { document.title = text; return document.title; }", "New Title" ).await?; println!("New title: {}", result); // Evaluate and deserialize complex object let info: PageInfo = page.eval( "() => ({ title: document.title, url: location.href, width: window.innerWidth, height: window.innerHeight })" ).await?; println!("Page info: {:?}", info); // Evaluate on specific element let link_text: String = page.evaluate_on_selector( "a", "el => el.textContent", None::<()> ).await?; println!("First link text: {}", link_text); browser.close().await?; Ok(()) } ``` -------------------------------- ### Rust: Wait Strategies for Playwright Source: https://context7.com/octaltree/playwright-rust/llms.txt Demonstrates various wait strategies in Playwright for Rust, including waiting for navigation (NetworkIdle), element selection, custom functions, and timeouts. Requires the 'playwright' and 'tokio' crates. ```rust use playwright::Playwright; use playwright::api::DocumentLoadState; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; // Wait for navigation to complete page.goto_builder("https://example.com/") .wait_until(Some(DocumentLoadState::NetworkIdle)) .goto() .await?; // Wait for selector to appear let element = page.wait_for_selector_builder("div.content") .timeout(Some(10000.0)) .wait_for_selector() .await?; println!("Element found: {}", element.is_some()); // Wait for function to return true page.wait_for_function_builder("() => document.readyState === 'complete'") .timeout(Some(5000.0)) .wait_for_function() .await?; // Wait for timeout (sleep) page.wait_for_timeout(2000.0).await; browser.close().await?; Ok(()) } ``` -------------------------------- ### Fill Forms and Interact with Elements in Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt Demonstrates how to fill text inputs, select dropdown options, check checkboxes, and interact with elements using Playwright in Rust. It requires the Playwright library and Tokio for asynchronous operations. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; page.goto_builder("https://example.com/form").goto().await?; // Fill text input page.fill_builder("input#username", "john_doe").fill().await?; // Type with delay between keystrokes page.type_builer("input#password", "secret123") .delay(Some(100.0)) .r#type() .await?; // Check checkbox page.check_builder("input[type='checkbox']#agree") .check() .await?; // Select dropdown option page.select_option_builder("select#country") .value("US") .select_option() .await?; // Press keyboard key page.press_builder("input#search", "Enter") .press() .await?; // Hover over element page.hover_builder("button.tooltip").hover().await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Generate Screenshots and PDFs in Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt This code snippet demonstrates how to capture full-page screenshots, screenshots with a clipped region, and generate PDF documents from web pages using Playwright in Rust. It requires Playwright, Tokio, and std::path::PathBuf. PDF generation is supported only in Chromium headless mode. ```rust use playwright::Playwright; use std::path::PathBuf; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; page.goto_builder("https://example.com/").goto().await?; // Take screenshot - full page let screenshot_bytes = page.screenshot_builder() .full_page(Some(true)) .path(Some(PathBuf::from("screenshot.png"))) .screenshot() .await?; println!("Screenshot size: {} bytes", screenshot_bytes.len()); // Take screenshot with custom clip region let clipped = page.screenshot_builder() .clip(Some(playwright::api::FloatRect { x: 0.0, y: 0.0, width: 800.0, height: 600.0, })) .screenshot() .await?; // Generate PDF (Chromium headless only) page.pdf_builder() .path(Some(PathBuf::from("page.pdf"))) .format(Some("A4")) .print_background(Some(true)) .pdf() .await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Handling Page Events with Playwright Rust Source: https://context7.com/octaltree/playwright-rust/llms.txt Subscribes to and handles various page events like requests, responses, and console messages using Playwright in Rust. It requires the 'playwright' and 'tokio' crates. The function takes no direct inputs but navigates to a URL and processes events, outputting them to the console until the 'Load' event is received. ```rust use playwright::Playwright; use playwright::api::page::{Event, EventType}; #[tokio::main] async fn main() -> Result<(), playwright::Error> { let playwright = Playwright::initialize().await?; playwright.prepare()?; let chromium = playwright.chromium(); let browser = chromium.launcher().headless(true).launch().await?; let context = browser.context_builder().build().await?; let page = context.new_page().await?; // Subscribe to events let mut event_stream = page.subscribe_event()?; // Navigate in background let page_clone = page.clone(); tokio::spawn(async move { page_clone.goto_builder("https://example.com/").goto().await.ok(); }); // Handle events while let Some(event) = event_stream.recv().await { match event { Event::Request(request) => { let url = request.url()?; let method = request.method()?; println!("Request: {} {}", method, url); }, Event::Response(response) => { let url = response.url()?; let status = response.status()?; println!("Response: {} - {}", url, status); }, Event::Console(msg) => { let text = msg.text()?; println!("Console: {}", text); }, Event::Load => { println!("Page loaded!"); break; }, _ => {} // Ignore other event types } } browser.close().await?; Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.