rustenium 1.1.9

A modern, robust, high-performance WebDriver BiDi automation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# Rustenium

The most robust, high-performance multi-protocol browser automation library for Rust.

Rustenium provides a powerful and ergonomic API for browser automation using the WebDriver BiDi and Chrome DevTools Protocol (CDP). It offers both low-level control and high-level abstractions for common automation tasks, with the ability to use BiDi and CDP independently or together.

Like Puppeteer / Playwright, but for RUST.

## Features

- **Dual Protocol Support**: Full WebDriver BiDi and Chrome DevTools Protocol (CDP) support
- **Multi-Browser**: Chrome and Firefox support out of the box
- **Flexible Launch Modes**: Manage the browser yourself, connect to an existing instance, or let the driver handle it
- **Optional Protocols**: Enable BiDi, CDP, or both — connect and disconnect at runtime
- **Auto-Download**: Automatically downloads Chrome, chromedriver, and Firefox if not present
- **Flexible Input Methods**:
  - **BidiMouse**: Direct, precise mouse movements for fast automation
  - **HumanMouse**: Realistic mouse movements with Bezier curves and jitter to mimic human behavior
  - **Keyboard**: Full keyboard support with modifier keys
  - **Touchscreen**: Multi-touch gesture support for mobile testing
- **CSS & XPath Selectors**: Convenient macros (`css!()`, `xpath!()`) for element location
- **Screenshot Capture**: Take screenshots of elements or entire pages
- **Network Interception**: Monitor and intercept network requests with BiDi
- **Event System**: Subscribe to browser events in real-time
- **Script Evaluation**: Execute JavaScript with preload script support
- **Timezone Emulation**: Emulate different timezones for testing
- **Device Emulation**: Emulate device metrics via CDP for responsive testing
- **Tab Management**: Create and manage browser tabs via CDP
- **Type-Safe API**: Leverages Rust's type system for compile-time safety

## Installation

Add Rustenium to your `Cargo.toml`:

```toml
[dependencies]
rustenium = { version = "1.0.1", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
```

## Browser Support

### Chrome

Chrome uses chromedriver for BiDi and connects directly for CDP. Both protocols can be used independently or together.

```rust
use rustenium::browsers::{chrome, ChromeConfig, ChromeLaunchMode};

// Default — Rustenium starts Chrome and attaches chromedriver
let mut browser = chrome(None).await;

// DriverManaged — Chromedriver spawns and manages Chrome
let config = ChromeConfig {
    launch_mode: ChromeLaunchMode::DriverManaged,
    ..Default::default()
};
let mut browser = chrome(Some(config)).await;

// Remote — Connect to an existing Chrome instance
let config = ChromeConfig {
    launch_mode: ChromeLaunchMode::Remote(9222),
    ..Default::default()
};
let mut browser = chrome(Some(config)).await;
```

### Firefox

Firefox has built-in WebDriver BiDi support — no separate driver needed. Rustenium connects directly to Firefox's BiDi WebSocket.

```rust
use rustenium::browsers::{firefox, FirefoxConfig, FirefoxLaunchMode};

// Default — Rustenium starts Firefox and connects directly
let mut browser = firefox(None).await;

// With custom config
let config = FirefoxConfig {
    remote_debugging_port: Some(9222),
    browser_flags: Some(vec!["--headless".to_string()]),
    ..Default::default()
};
let mut browser = firefox(Some(config)).await;

// Remote — Connect to an existing Firefox instance
let config = FirefoxConfig {
    launch_mode: FirefoxLaunchMode::Remote(9222),
    ..Default::default()
};
let mut browser = firefox(Some(config)).await;
```

## Protocol Selection (Chrome)

BiDi is enabled by default. CDP is opt-in. You can use them independently or together,
though note that CDP can become buggy in the presence of an active BiDi connection.
Connecting BiDi after CDP does not affect the CDP setup.

```rust
use rustenium::browsers::ChromeConfig;

// BiDi only (default)
let config = ChromeConfig::default();

// CDP only
let config = ChromeConfig {
    enable_bidi: false,
    enable_cdp: true,
    ..Default::default()
};

// Both
let config = ChromeConfig {
    enable_bidi: true,
    enable_cdp: true,
    ..Default::default()
};
```

You can also connect protocols at runtime:

```rust
use rustenium::browsers::{ChromeBrowser, ChromeConfig};

// Start with CDP only, then connect BiDi later
let mut browser = ChromeBrowser::new(ChromeConfig {
    enable_bidi: false,
    enable_cdp: true,
    ..Default::default()
}).await;

// ... do CDP work ...

browser.connect_bidi().await; // connects BiDi without affecting CDP
```

## Quick Start

```rust
use rustenium::browsers::chrome;
use rustenium_macros::css;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a Chrome browser instance
    let mut browser = chrome(None).await;

    // Navigate to a page
    browser.navigate("https://example.com").await?;

    // Find and interact with elements
    let search_box = browser.find_node(css!("input[type='search']")).await?.expect("No node found");
    search_box.screenshot().await?;

    let mut submit_button = browser.find_node(css!("button[type='submit']")).await?.expect("No node found");
    submit_button.mouse_click().await?;

    // Take a screenshot
    browser.screenshot().await?;

    // Close the browser
    browser.close().await?;

    Ok(())
}
```

## Examples

### Browser Setup and Navigation (BiDi)

```rust
use rustenium::browsers::{chrome, ChromeConfig, NavigateOptionsBuilder};
use rustenium_bidi_definitions::browsing_context::types::ReadinessState;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = ChromeConfig::default();

    config.capabilities.add_arg("--disable-gpu")
        .add_args(["--window-size=1920,1080"])
        .accept_insecure_certs(true);

    let mut browser = chrome(Some(config)).await;

    // Navigate and wait for load
    browser.navigate_with_options("https://example.com",
        NavigateOptionsBuilder::default()
            .wait(ReadinessState::Interactive)
            .build()
    ).await?;

    browser.close().await?;
    Ok(())
}
```

### CDP Navigation and Tab Management

```rust
use rustenium::browsers::{ChromeConfig, ChromeBrowser};
use rustenium::browsers::cdp_browser::CdpBrowser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = ChromeBrowser::new(ChromeConfig {
        enable_bidi: false,
        enable_cdp: true,
        ..Default::default()
    }).await;

    // Navigate via CDP
    CdpBrowser::navigate(&mut browser, "https://example.com").await?;

    // Create a new tab
    CdpBrowser::create_tab(&mut browser, "https://example.org").await?;

    // Emulate device metrics
    CdpBrowser::emulate_device_metrics(&mut browser, 375, 812, 3.0, true).await?;

    Ok(())
}
```

### Finding Elements

```rust
use rustenium::browsers::chrome;
use rustenium_macros::{css, xpath};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;
    browser.navigate("https://example.com").await?;

    // Using CSS selectors
    let element = browser.find_node(css!("#my-id")).await?;
    let buttons = browser.find_nodes(css!(".btn-primary")).await?;

    // Using XPath
    let headers = browser.find_nodes(xpath!("//h1[@class='title']")).await?;

    // Wait for elements to appear
    let node = browser.wait_for_node(css!(".dynamic-content")).await?;

    browser.close().await?;
    Ok(())
}
```

### Mouse Input — Precise Movements

```rust
use rustenium::browsers::chrome;
use rustenium::input::{MouseMoveOptions, MouseClickOptions, Point};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;
    let context_id = browser.get_active_context_id()?;

    // Instant, precise movements
    browser.mouse().move_to(Point { x: 100.0, y: 200.0 }, &context_id, MouseMoveOptions {
        steps: Some(5),
        ..Default::default()
    }).await?;

    browser.mouse().click(None, &context_id, MouseClickOptions::default()).await?;

    browser.close().await?;
    Ok(())
}
```

### Mouse Input — Human-Like Movements

```rust
use rustenium::browsers::chrome;
use rustenium::input::{MouseMoveOptions, MouseClickOptions, Point};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;
    let context_id = browser.get_active_context_id()?;

    // Realistic movements with Bezier curves and jitter
    browser.human_mouse().move_to(Point { x: 100.0, y: 200.0 }, &context_id, MouseMoveOptions::default()).await?;
    browser.human_mouse().click(None, &context_id, MouseClickOptions::default()).await?;

    browser.close().await?;
    Ok(())
}
```

### Keyboard Input

```rust
use rustenium::browsers::chrome;
use rustenium::input::KeyboardTypeOptions;
use rustenium_macros::css;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;
    let context_id = browser.get_active_context_id()?;

    browser.navigate("https://example.com").await?;

    let text = browser.wait_for_node(css!("#text")).await?.expect("No node exists");

    // Type text with delay between keystrokes
    browser.keyboard().type_text(
        &text.get_inner_text().await,
        &context_id,
        Some(KeyboardTypeOptions { delay: Some(36) }),
    ).await?;

    // Modifier key combinations (Ctrl+A)
    browser.keyboard().down("Control", &context_id).await?;
    browser.keyboard().press("a", &context_id, None).await?;
    browser.keyboard().up("Control", &context_id).await?;

    browser.close().await?;
    Ok(())
}
```

### Network Interception

```rust
use rustenium::browsers::chrome;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;

    // Intercept and handle network requests
    browser.on_request(|request| async move {
        println!("Request URL: {}", request.url());

        if request.url().contains("ads.example.com") {
            let _ = request.abort().await;
            return;
        }
        request.continue_().await;
    }).await?;

    // Add authentication handler
    browser.authenticate("username", "password").await?;

    browser.navigate("https://example.com").await?;

    browser.close().await?;
    Ok(())
}
```

### Script Evaluation & Preload Scripts

```rust
use rustenium::browsers::chrome;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;

    // Evaluate JavaScript
    let result = browser.evaluate_script(
        "document.title".to_string(),
        true,
    ).await?;

    // Add a preload script that runs on every page load
    let script_id = browser.add_preload_script(
        "() => { window.__injected = true; }".to_string(),
    ).await?;

    // Remove it later
    browser.remove_preload_script(script_id).await?;

    browser.close().await?;
    Ok(())
}
```

### Timezone Emulation

```rust
use rustenium::browsers::chrome;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = chrome(None).await;

    browser.emulate_timezone(Some("Asia/Tokyo".to_string())).await?;
    browser.navigate("https://example.com").await?;

    browser.close().await?;
    Ok(())
}
```

### Firefox Example

```rust
use rustenium::browsers::firefox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut browser = firefox(None).await;

    browser.navigate("https://example.com").await?;

    // All BiDi features work the same as Chrome
    let nodes = browser.find_nodes(css!("h1")).await?;
    browser.screenshot().await?;

    browser.close().await?;
    Ok(())
}
```

## Crate Structure

| Crate | Description |
|---|---|
| `rustenium` | Main library — browser impls, input devices, node interactions |
| `rustenium-core` | Protocol transport, sessions, connections, event system |
| `rustenium-bidi-definitions` | WebDriver BiDi protocol type definitions |
| `rustenium-cdp-definitions` | Chrome DevTools Protocol type definitions |
| `rustenium-macros` | Procedural macros (`css!`, `xpath!`) |
| `rustenium-generator` | Code generator for protocol definitions from specs |

## Browser Support

| Browser | BiDi | CDP | Auto-Download |
|---|---|---|---|
| Chrome/Chromium | Yes | Yes | Yes |
| Firefox | Yes | No | Yes |

## Requirements

- Rust 1.85 or later (2024 edition)
- Chrome or Firefox (auto-downloaded if not present)

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Acknowledgements

- [HumanCursor]https://github.com/riflosnake/HumanCursor — the human-like mouse trajectory algorithm (Bezier curves, easing, Gaussian distortion) is ported from this excellent Python library
- [Chromium Oxide]https://github.com/mattsse/chromium-oxide — inspiration for the protocol definition code generator
- [The Ish Bot]https://github.com/dashn9/ish-adf-bot — some bot automation inspiration was borrowed from this project

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.