[dependencies]
regex = "1.5.4"
reqwest = { version = "0.11", features = ["blocking", "json"] }
use regex::Regex;
use reqwest::blocking::get;
use std::fs::{self, File};
use std::io::{copy, Error};
use std::path::Path;
fn download_images(text: &str, save_path: &str) -> Result<(), Error> {
// 创建保存路径文件夹
if let Err(e) = fs::create_dir_all(save_path) {
eprintln!("创建文件夹失败: {} - 错误: {}", save_path, e);
return Err(e);
}
// 正则表达式匹配图片链接
let re = Regex::new(r"https://\S+\.(jpg|png|jpeg)").unwrap();
// 遍历匹配到的链接
for cap in re.captures_iter(text) {
let url = &cap[0];
println!("匹配到的图片链接: {}", url);
// 下载图片
match get(url) {
Ok(response) => {
let file_name = url.split('/').last().unwrap();
let file_path = Path::new(save_path).join(file_name);
match File::create(&file_path) {
Ok(mut file) => {
if let Err(e) = copy(&mut response.bytes().unwrap().as_ref(), &mut file) {
eprintln!("保存图片失败: {} - 错误: {}", file_path.display(), e);
} else {
println!("图片已下载: {}", file_path.display());
}
}
Err(e) => eprintln!("创建文件失败: {} - 错误: {}", file_path.display(), e),
}
}
Err(e) => eprintln!("下载图片失败: {} - 错误: {}", url, e),
}
}
Ok(())
}
fn main() -> Result<(), Error> {
// 示例文本
let text = r#"
https://xxxxx/1.jpg
https://xxxxx/a4b.png
https://xxxxx/4b.jpeg
"#;
// 指定保存路径
let save_path = "path/to/save/images";
// 调用下载图片的函数
download_images(text, save_path)?;
Ok(())
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询