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
相关推荐
Kapaseker30 分钟前
深入 Rust 迭代器(中)
rust
muyouking111 小时前
Rust + WASM + Svelte 深度实战:内存管理、性能权衡与图像处理进阶
开发语言·rust·wasm
2301_795167201 小时前
玩转Rust高级应用 如何进行面向对象设计模式的实现,实现状态模式
设计模式·rust·状态模式
2301_796512522 小时前
Rust编程学习 - 如何快速构建一个单线程 web server
前端·学习·rust
想不明白的过度思考者10 小时前
Rust——异步递归深度指南:从问题到解决方案
开发语言·后端·rust
逻极12 小时前
Rust数据类型(上):标量类型全解析
开发语言·后端·rust
Zhangzy@12 小时前
Rust 编译优化选项
android·开发语言·rust
百锦再12 小时前
第2章 第一个Rust程序
java·开发语言·后端·rust·eclipse·tomcat·hibernate
Zhangzy@12 小时前
Rust 中的注释与文档注释实践指南
开发语言·后端·rust
alwaysrun12 小时前
Rust编译参数与优化控制
rust·cargo·rustc·profile·strip·lto