• Stars
    star
    1,085
  • Rank 42,662 (Top 0.9 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A high-level API for programmatically interacting with web pages through WebDriver.

fantoccini

Crates.io Documentation codecov Gitter chat

A high-level API for programmatically interacting with web pages through WebDriver.

This crate uses the WebDriver protocol to drive a conforming (potentially headless) browser through relatively high-level operations such as "click this element", "submit this form", etc.

Most interactions are driven by using CSS selectors. With most WebDriver-compatible browser being fairly recent, the more expressive levels of the CSS standard are also supported, giving fairly powerful operators.

Forms are managed by first calling Client::form, and then using the methods on Form to manipulate the form's fields and eventually submitting it.

For low-level access to the page, Client::source can be used to fetch the full page HTML source code, and Client::raw_client_for to build a raw HTTP request for a particular URL.

Examples

These examples all assume that you have a WebDriver compatible process running on port 4444. A quick way to get one is to run geckodriver at the command line.

Let's start out clicking around on Wikipedia:

use fantoccini::{ClientBuilder, Locator};

// let's set up the sequence of steps we want the browser to take
#[tokio::main]
async fn main() -> Result<(), fantoccini::error::CmdError> {
    let c = ClientBuilder::native().connect("http://localhost:4444").await.expect("failed to connect to WebDriver");

    // first, go to the Wikipedia page for Foobar
    c.goto("https://en.wikipedia.org/wiki/Foobar").await?;
    let url = c.current_url().await?;
    assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foobar");

    // click "Foo (disambiguation)"
    c.find(Locator::Css(".mw-disambig")).await?.click().await?;

    // click "Foo Lake"
    c.find(Locator::LinkText("Foo Lake")).await?.click().await?;

    let url = c.current_url().await?;
    assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foo_Lake");

    c.close().await
}

How did we get to the Foobar page in the first place? We did a search! Let's make the program do that for us instead:

// -- snip wrapper code --
// go to the Wikipedia frontpage this time
c.goto("https://www.wikipedia.org/").await?;
// find the search form, fill it out, and submit it
let f = c.form(Locator::Css("#search-form")).await?;
f.set_by_name("search", "foobar").await?
 .submit().await?;

// we should now have ended up in the right place
let url = c.current_url().await?;
assert_eq!(url.as_ref(), "https://en.wikipedia.org/wiki/Foobar");

// -- snip wrapper code --

What if we want to download a raw file? Fantoccini has you covered:

// -- snip wrapper code --
// go back to the frontpage
c.goto("https://www.wikipedia.org/").await?;
// find the source for the Wikipedia globe
let img = c.find(Locator::Css("img.central-featured-logo")).await?;
let src = img.attr("src").await?.expect("image should have a src");
// now build a raw HTTP client request (which also has all current cookies)
let raw = img.client().raw_client_for(fantoccini::Method::GET, &src).await?;

// we then read out the image bytes
use futures_util::TryStreamExt;
let pixels = raw
    .into_body()
    .try_fold(Vec::new(), |mut data, chunk| async move {
        data.extend_from_slice(&chunk);
        Ok(data)
    })
    .await
    .map_err(fantoccini::error::CmdError::from)?;
// and voilà, we now have the bytes for the Wikipedia logo!
assert!(pixels.len() > 0);
println!("Wikipedia logo is {}b", pixels.len());

// -- snip wrapper code --

For more examples, take a look at the examples/ directory.

Contributing to fantoccini

The following information applies only to developers interested in contributing to this project. If you simply want to use it to automate web browsers you can skip this section.

How to run tests

The tests assume that you have chromedriver and geckodriver already running on your system. You can download them using the links above. Then run them from separate tabs in your terminal. They will stay running until terminated with Ctrl+C or until the terminal session is closed.

Then run cargo test from this project directory.

More Repositories

1

left-right

A lock-free, read-optimized, concurrency primitive.
Rust
1,940
star
2

inferno

A Rust port of FlameGraph
Rust
1,642
star
3

configs

My configuration files
Vim Script
968
star
4

bus

Efficient, lock-free, bounded Rust broadcast channel
Rust
668
star
5

flurry

A port of Java's ConcurrentHashMap to Rust
Rust
516
star
6

rust-tcp

A learning experience in implementing TCP in Rust
Rust
488
star
7

rust-imap

IMAP client library for Rust
Rust
477
star
8

evmap

A lock-free, eventually consistent, concurrent multi-value map.
Rust
459
star
9

drwmutex

Distributed RWMutex in Go
Go
323
star
10

rust-ci-conf

Collection of CI configuration files for Rust projects
278
star
11

rustengan

https://fly.io/dist-sys/ in Rust
Rust
260
star
12

roget

Wordle Solver inspired by 3blue1brown
Rust
224
star
13

haphazard

Hazard pointers in Rust.
Rust
193
star
14

griddle

A HashMap variant that spreads resize load across inserts
Rust
188
star
15

stream-cancel

A Rust library for interrupting asynchronous streams.
Rust
155
star
16

wewerewondering

wewerewondering.com
Rust
154
star
17

tsunami

Rust crate for running one-off cloud jobs
Rust
154
star
18

faktory-rs

Rust bindings for Faktory clients and workers
Rust
149
star
19

rust-for-rustaceans.com

Source for https://rust-for-rustaceans.com/
CSS
146
star
20

buzz

A simple system tray application for notifying about unseen e-mail
Rust
129
star
21

volley

Volley is a benchmarking tool for measuring the performance of server networking stacks.
C
121
star
22

msql-srv

Bindings for writing a server that can act as MySQL/MariaDB
Rust
116
star
23

proximity-sort

Simple command-line utility for sorting inputs by proximity to a path argument
Rust
116
star
24

bustle

A benchmarking harness for concurrent key-value collections
Rust
114
star
25

tracing-timing

Inter-event timing metrics on top of tracing.
Rust
112
star
26

stuck

Rust
107
star
27

atone

A `VecDeque` (and `Vec`) variant that spreads resize load across pushes.
Rust
106
star
28

rust-ibverbs

Bindings for RDMA ibverbs through rdma-core
Rust
106
star
29

thesis

My PhD thesis (eventually)
TeX
93
star
30

openssh-rs

Scriptable SSH through OpenSSH in Rust
Rust
92
star
31

superimposer

Python
85
star
32

udp-over-tcp

A command-line tool for tunneling UDP datagrams over TCP.
Rust
84
star
33

tetris-tutorial

From rags to riches; building Tetris with no programming experience.
JavaScript
78
star
34

codecrafters-bittorrent-rust

Rust
78
star
35

orst

Sorting algorithms in Rust
Rust
76
star
36

async-ssh

High-level Rust library for asynchronous SSH connections
Rust
74
star
37

codecrafters-git-rust

Rust
73
star
38

pthread_pool

A simple implementation of thread pooling for C/C++ using POSIX threads
C
71
star
39

arrav

A sentinel-based, heapless, `Vec`-like type.
Rust
68
star
40

streamsh

Download online video streams using shell
Shell
67
star
41

trawler

Workload generator that emulates the traffic pattern of lobste.rs
Rust
66
star
42

async-bincode

Asynchronous access to a bincode-encoded item stream.
Rust
66
star
43

sento

A lock-free, append-only atomic pool.
Rust
65
star
44

hashbag

An unordered multiset/bag implementation backed by HashMap
Rust
64
star
45

cucache

Fast PUT/GET/DELETE in-memory key-value store for lookaside caching
Go
63
star
46

wp2ghost

Convert WordPress XML exports to Ghost JSON import files
JavaScript
58
star
47

vast-vmap

JavaScript library for IAB VAST + VMAP
JavaScript
56
star
48

lox

https://app.codecrafters.io/courses/interpreter
Rust
55
star
49

vote.rs

Simple website for doing multi-round ranked choice voting
Rust
52
star
50

tokio-io-pool

An I/O-oriented tokio runtime thread pool
Rust
48
star
51

hurdles

Rust library providing a counter-based thread barrier
Rust
46
star
52

ordsearch

A Rust data structure for efficient lower-bound lookups
Rust
42
star
53

arccstr

Thread-safe, reference-counted null-terminated immutable Rust strings.
Rust
41
star
54

cliff

Find the load at which a benchmark falls over.
Rust
36
star
55

curb

Run a process on a particular subset of the available hardware.
Rust
35
star
56

bystander

Rust
30
star
57

shortcut

Rust crate providing an indexed, queryable column-based storage system
Rust
30
star
58

hasmail

Simple tray icon for detecting new email on IMAP servers
Go
29
star
59

ornithology

A tool that parses your Twitter archive and highlights interesting data from it.
Rust
28
star
60

rust-zipf

Rust implementation of a fast, bounded, Zipf-distributed random number generator
Rust
26
star
61

minion

Rust crate for managing cancellable services
Rust
24
star
62

cargo-index-transit

A package for common types for Cargo index interactions, and conversion between them.
Rust
24
star
63

streamunordered

A version for futures::stream::FuturesUnordered that multiplexes Streams
Rust
24
star
64

icebreaker

Web app that allows students to ask real-time, anonymous questions during class
Go
23
star
65

mktrayicon

Create system tray icons by writing to a pipe
C
22
star
66

thesquareplanet.com

My homepage
HTML
20
star
67

rust-basic-hashmap

Let's build a HashMap
Rust
20
star
68

obs-do

CLI for common OBS operations while streaming using WebSocket
Rust
20
star
69

gladia-captions

Rust
20
star
70

PHP-Browser

A PHP class to allow scripts to access online resources hidden behind login-forms and other user-interaction measures
PHP
19
star
71

keybase-chat-notifier

Simple desktop notifier for keybase chat
Rust
19
star
72

tokio-byteorder

Asynchronous adapter for byteorder
Rust
19
star
73

python-agenda

Python module for pretty task logging
Python
18
star
74

async-lease

An asynchronous leased value
Rust
17
star
75

yambar-hyprland-wses

Rust
17
star
76

tally

time's prettier cousin
Rust
15
star
77

strawpoll

Rust
15
star
78

async-option

Asynchronous Arc<Mutex<Option<T>>>
Rust
14
star
79

indexmap-amortized

bluss/IndexMap with amortized resizes
Rust
14
star
80

tokio-os-timer

Timer facilities for Tokio based on OS-level primitives.
Rust
14
star
81

cloud-arch

Script for generating Arch Linux cloud images
Shell
13
star
82

cryptsetup-gui

Simple GUI for unlocking cryptsetup volumes
C
13
star
83

guardian

Owned mutex guards for refcounted mutexes.
Rust
12
star
84

rust-at-sunrise

Tool for posting daily updates on the latest available Rust Nightly
Rust
11
star
85

experiment

A tool for running concurrent multi-configuration experiments.
Ruby
11
star
86

mio-pool

A pool of workers operating on a single set of mio connections
Rust
10
star
87

rust-agenda

Simple, pretty CLI progress tracker
Rust
10
star
88

songtext

Simple bash script for retrieving song lyrics.
Shell
10
star
89

skyline

Various implementations of tower::Service
Rust
9
star
90

hanabot

Hanabi Slack bot
Rust
8
star
91

cleaver

Data-flow distribution analyzer
Rust
8
star
92

repackage

A terrible and nerve-inducing tool to rename a crate in a .crate file
Rust
7
star
93

simio

I/O Automata Simulator
Python
7
star
94

cargo-http-bench

Benchmarking suite for Cargo's experimental HTTP registry implementation
Shell
7
star
95

go-iprof

Simple go library for concurrent instrumented profiling.
Go
7
star
96

incomplete

Provides incomplete!(), a compile-time checked version of Rust's unimplemented!() macro
Rust
7
star
97

rucache

Fast PUT/GET/DELETE in-memory key-value store for lookaside caching -- Rust prototype
Rust
6
star
98

throttled-reader

An io::Read proxy that limits calls to read()
Rust
6
star
99

ff-jump-to-tab

A (subjectively) better Ctrl+# experience for Firefox
JavaScript
6
star
100

snavi

Sane navigation enhancement with Javascript
JavaScript
6
star