rust 下载文件与剧作家箱

oxosxuxt  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(100)

我试图使用Playwright库访问网站并下载rust中的文件,但我在web上找不到函数示例。我正在努力,但我不能从这一点上前进。完成我的代码并进行下载缺少什么?

use playwright::{Playwright, api::{Download, download}};
use tokio;

#[tokio::main]
async fn main() -> Result<(), playwright::Error> {

    let playwright = Playwright::initialize().await?;
    playwright.prepare()?; // Install browsers
    let chromium = playwright.chromium();
    let browser = chromium.launcher().headless(false).launch().await?;
    let context = browser.context_builder().build().await?;
    let page = context.new_page().await?;
    page.goto_builder("https://demoqa.com/upload-download").goto().await?;

    // playwright::api::download::Download - save_as() - suggested_filename() - url() - path()

    page.click_builder("a:has-text(\"Download\")").click().await.expect("");
    let my_download = page.expect_event(playwright::api::page::EventType::Download).await?;


    page.wait_for_timeout(5000 as f64).await;
    browser.close().await.expect("erro ao fechar navegador");

    Ok(())

}
yjghlzjz

yjghlzjz1#

我知道了!我希望这对将来的人有帮助...

use std::path::PathBuf;
use playwright::{Playwright, api::page};

#[tokio::main]
async fn main() -> Result<(), playwright::Error> {

    let playwright = Playwright::initialize().await?;
    playwright.prepare()?; // Install browsers
    let chromium = playwright.chromium();
    let browser = chromium.launcher().headless(false).launch().await?;
    let context = browser.context_builder().accept_downloads(true).build().await?;

    let page = context.new_page().await?;
    page.goto_builder("https://demoqa.com/upload-download").goto().await?;

    let (d, _) = tokio::join!(
        page.expect_event(page::EventType::Download),
        page.click_builder("a:has-text(\"Download\")").click()
    ); 

    let download = match d.unwrap() {
        page::Event::Download(d) => d,
        _ => unreachable!()
    }; 

    let caminho = PathBuf::new().join("/home/paulo/tmp").join(download.suggested_filename());
    download.save_as(caminho).await.unwrap();  

    page.close(None).await.unwrap();

    page.wait_for_timeout(5000 as f64).await;
    browser.close().await.expect("erro ao fechar navegador");     

    Ok(())

}

相关问题