Lines
93.24 %
Functions
85.71 %
Branches
100 %
//! A minimal W3C WebDriver client for chromedriver.
use anyhow::{Context, Result, anyhow, bail};
use base64::Engine;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{Method, Request};
use hyper_util::client::legacy::{Client, connect::HttpConnector};
use hyper_util::rt::TokioExecutor;
use serde_json::{Value, json};
use std::time::{Duration, Instant};
use super::harness::READY_DEADLINE;
const NO_SUCH_ELEMENT: &str = "no such element";
const FIND_POLL: Duration = Duration::from_millis(100);
const ELEMENT: &str = "element-6066-11e4-a52e-4f735466cecf";
/// Keys of the WebDriver key table.
pub const ARROW_DOWN: &str = "\u{E015}";
pub const ENTER: &str = "\u{E007}";
pub const TAB: &str = "\u{E004}";
pub const SHIFT_TAB: &str = "\u{E008}\u{E004}\u{E000}";
pub const BACKSPACE: &str = "\u{E003}";
#[derive(Clone)]
pub struct Element(String);
pub struct Driver {
client: Client<HttpConnector, Full<Bytes>>,
session: String,
}
async fn call(
client: &Client<HttpConnector, Full<Bytes>>,
method: Method,
url: &str,
body: Option<Value>,
) -> Result<Value> {
let payload = body.map_or_else(String::new, |body| body.to_string());
let request = Request::builder()
.method(method)
.uri(url)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(payload)))?;
let response = client.request(request).await?;
let status = response.status();
let bytes = response.into_body().collect().await?.to_bytes();
let reply: Value = serde_json::from_slice(&bytes)
.with_context(|| format!("{url}: {}", String::from_utf8_lossy(&bytes)))?;
if !status.is_success() {
bail!("{url} answered {status}: {}", reply["value"]);
Ok(reply["value"].clone())
impl Driver {
/// A headless Chrome session through the chromedriver at `endpoint`.
pub async fn connect(endpoint: &str) -> Result<Self> {
let client = Client::builder(TokioExecutor::new()).build_http();
let capabilities = json!({
"capabilities": {"alwaysMatch": {
"browserName": "chrome",
"goog:loggingPrefs": {"browser": "ALL"},
"goog:chromeOptions": {"args": [
"--headless=new", "--no-sandbox", "--disable-gpu",
"--disable-dev-shm-usage", "--window-size=1280,900",
]}
}}
});
let reply = call(
&client,
Method::POST,
&format!("{endpoint}/session"),
Some(capabilities),
)
.await?;
let id = reply["sessionId"]
.as_str()
.ok_or_else(|| anyhow!("no session id in {reply}"))?;
Ok(Self {
client,
session: format!("{endpoint}/session/{id}"),
})
async fn post(&self, path: &str, body: Value) -> Result<Value> {
let url = format!("{}{path}", self.session);
call(&self.client, Method::POST, &url, Some(body)).await
async fn get(&self, path: &str) -> Result<Value> {
call(&self.client, Method::GET, &url, None).await
pub async fn quit(&self) -> Result<()> {
call(&self.client, Method::DELETE, &self.session, None)
.await
.map(drop)
pub async fn goto(&self, url: &str) -> Result<()> {
self.post("/url", json!({ "url": url })).await.map(drop)
pub async fn set_size(&self, width: u32, height: u32) -> Result<()> {
self.post("/window/rect", json!({ "width": width, "height": height }))
fn element(value: &Value) -> Result<Element> {
value[ELEMENT]
.map(|id| Element(id.to_string()))
.ok_or_else(|| anyhow!("not an element: {value}"))
/// The element that has the focus.
pub async fn active(&self) -> Result<Element> {
Self::element(&self.get("/element/active").await?)
pub async fn find_all(&self, css: &str) -> Result<Vec<Element>> {
let found = self
.post(
"/elements",
json!({ "using": "css selector", "value": css }),
found
.as_array()
.map(|list| list.iter().map(Self::element).collect())
.unwrap_or_else(|| Ok(Vec::new()))
/// Polls `path` while the element is absent; any other failure is final.
async fn find_waiting(&self, path: &str, css: &str, what: &str) -> Result<Element> {
let deadline = Instant::now() + READY_DEADLINE;
loop {
.post(path, json!({ "using": "css selector", "value": css }))
.await;
match found {
Ok(value) => return Self::element(&value),
Err(error) if !format!("{error:#}").contains(NO_SUCH_ELEMENT) => {
return Err(error).with_context(|| what.to_string());
Err(error) if Instant::now() > deadline => {
Err(_) => tokio::time::sleep(FIND_POLL).await,
pub async fn find(&self, css: &str) -> Result<Element> {
self.find_waiting("/element", css, &format!("find {css}"))
pub async fn find_in(&self, parent: &Element, css: &str) -> Result<Element> {
self.find_waiting(
&format!("/element/{}/element", parent.0),
css,
&format!("find {css} in an element"),
pub async fn click(&self, element: &Element) -> Result<()> {
self.post(&format!("/element/{}/click", element.0), json!({}))
pub async fn clear(&self, element: &Element) -> Result<()> {
self.post(&format!("/element/{}/clear", element.0), json!({}))
pub async fn type_into(&self, element: &Element, text: &str) -> Result<()> {
self.post(
&format!("/element/{}/value", element.0),
json!({ "text": text }),
/// Runs `script` with `args` (elements pass as themselves) and returns
/// its result.
pub async fn run(&self, script: &str, args: Vec<Value>) -> Result<Value> {
self.post("/execute/sync", json!({ "script": script, "args": args }))
/// Runs `script` with `args`; it returns by calling its last argument.
pub async fn run_async(&self, script: &str, args: Vec<Value>) -> Result<Value> {
self.post("/execute/async", json!({ "script": script, "args": args }))
pub async fn screenshot(&self) -> Result<Vec<u8>> {
let shot = self.get("/screenshot").await?;
let text = shot.as_str().ok_or_else(|| anyhow!("no screenshot"))?;
Ok(base64::engine::general_purpose::STANDARD.decode(text)?)
/// The browser log entries since the last call.
pub async fn log(&self) -> Result<Vec<Value>> {
let entries = self.post("/se/log", json!({ "type": "browser" })).await?;
Ok(entries.as_array().cloned().unwrap_or_default())