Rust Web自动化Demo

1.新建项目

使用RustCover新建项目,目录如下:

Cargo.toml文件

rust 复制代码
[package]
name = "Demo"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1", features = ["full"] }
thirtyfour = { version = "0.31.0", features = ["component"] }
scraper = "0.15.0"

2.编写代码

以百度网站为例

rust 复制代码
use std::time::Duration;
use thirtyfour::By;
use tokio;
use thirtyfour::prelude::{DesiredCapabilities, WebDriver, WebDriverResult};

#[tokio::test]
async fn navigate_to_url() -> WebDriverResult<()> {
    let capabilities = DesiredCapabilities::chrome();
    let driver = WebDriver::new("http://localhost:9515", capabilities)
        .await
        .expect("Failed to connect to localhost:9515!");
    driver.maximize_window().await?;
    driver.set_implicit_wait_timeout(std::time::Duration::from_secs(10)).await?;
    tokio::time::sleep(Duration::from_secs(3)).await;
    driver
        .goto("https://www.baidu.com")
        .await
        .expect("Couldn't navigate to the URL!");
    tokio::time::sleep(Duration::from_secs(2)).await;
    let search_input = driver.find(By::Id("kw")).await?;
    search_input.send_keys("Hello").await?;
    tokio::time::sleep(Duration::from_secs(2)).await;
    let search_button = driver.find(By::Id("su")).await?;
    search_button.click().await?;
    tokio::time::sleep(Duration::from_secs(2)).await;
    let page_title = driver.title()
        .await
        .expect("Page title not found");
    driver.quit().await?;
    assert_eq!(
        page_title,
        "Hello_百度搜索"
    );
    Ok(())
}

3.运行项目

在RustCover打开终端,输入命令:

bash 复制代码
chromedriver --port=9515

然后再新建终端,输入命令:

bash 复制代码
cargo test
相关推荐
古城小栈8 小时前
Rust 调用 C 语言库 实战指南(企业级)
c语言·开发语言·rust
刘布斯yy17 小时前
新写了个直播录制工具,可录制抖音快手斗鱼直播
rust·音视频·直播录制
恋喵大鲤鱼20 小时前
Rust 中的字符串 slice 是什么?
rust
迷渡2 天前
用 Rust 重写的 Bun 有 13365 个 unsafe!
开发语言·后端·rust
咸甜适中2 天前
rust语言学习笔记Trait(九)PartialEq、 Eq(相等比较)
笔记·学习·rust
恋喵大鲤鱼2 天前
Rust 中 package crate 和 module 的关系
rust
Rust研习社2 天前
Rust 官方拟定 LLM 政策,防止 LLM 污染开源社区?
开发语言·后端·ai·rust·开源
techdashen2 天前
Async Rust 近况补课:从 `async-trait` 到原生 async trait
网络·算法·rust
techdashen2 天前
在 Async Rust 中实现请求合并(Request Coalescing)
开发语言·后端·rust
咸甜适中3 天前
rust语言学习笔记Trait(八)Iterator(迭代器)
笔记·学习·rust