利用HtmlAgilityPack插件写的一个抓取指定网页的图片 第一次写 很乱 随便看看就行...

本文主要是介绍利用HtmlAgilityPack插件写的一个抓取指定网页的图片 第一次写 很乱 随便看看就行...,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


public partial class Form1 : Form
{
/// <summary>
/// 存放图片地址
/// </summary>
List<string> ImgList = new List<string>();
/// <summary>
/// 当前下载文件
/// </summary>
int _loadFile = 0;
//图片标题
string title = "";
/// <summary>
/// 文件总数
/// </summary>
int _totalFile = 0;
string[] exts = {
".bmp", ".dib", ".jpg", ".jpeg",
".jpe", ".jfif", ".png", ".gif",
".tif", ".tiff" };

public Form1()
{
InitializeComponent();

Control.CheckForIllegalCrossThreadCalls = false;

}

private void Form1_Load(object sender, EventArgs e)
{

this.comboBoxEdit1.Properties.Items.Add("UTF-8");
this.comboBoxEdit1.Properties.Items.Add("GB2312");
}
/// <summary>
/// 获取当前页面图片数量
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
getImgs();
}

/// <summary>
/// 下载图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
this.textBox1.Clear();
if (ImgList.Count <= 0) return;
//重置加载文件数
_loadFile = 0;
int index = 1;
Task.Factory.StartNew(() =>
{

foreach (var item in ImgList)
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
webClient.Proxy = null;
Uri uri = new Uri(item);

if (!Directory.Exists(System.Environment.CurrentDirectory + "\\Img"))
{
Directory.CreateDirectory(System.Environment.CurrentDirectory + "\\Img");

}
var imghouzhui = item.Substring(item.LastIndexOf(".")).Substring(0, 4);

 

string fileName = title == "" ? Guid.NewGuid().ToString() : title + "_" + index + imghouzhui;
webClient.DownloadFileAsync(uri, System.Environment.CurrentDirectory + "\\Img\\" + fileName);
index++;
}

 

});
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}

 


}
/// <summary>
/// 下载文件进度条
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.Invoke(new MethodInvoker(delegate
{
this.progressBar2.Value = e.ProgressPercentage;
this.label2.Text = string.Format("正在下载文件,完成进度{0}% {1}/{2}(字节)"
, e.ProgressPercentage
, e.BytesReceived
, e.TotalBytesToReceive);
}));

 

}
/// <summary>
/// 抓取https://www.mntup.com/网站写真
/// </summary>
public void getImgs()
{
this.textBox1.Clear();
this.progressBar1.Value = 0;
this.progressBar2.Value = 0;
this.label2.Text = "单个文件进度:";
this.label1.Text = "总进度:";
ImgList.Clear();
HtmlWeb htmlWeb = new HtmlWeb();
if (textBox2.Text.Trim().Length <= 0 || comboBoxEdit1.SelectedText == "")
{
return;
}
try
{
htmlWeb.OverrideEncoding = Encoding.GetEncoding(comboBoxEdit1.SelectedText.ToString());


int pageMinIndex = Convert.ToInt32(pageMin.Value);
int pageMaxIndex = Convert.ToInt32(pageMax.Value);
this.textBox1.AppendText("抓取到的图片地址");
for (int i = pageMinIndex; i <= pageMaxIndex; i++)
{
string url = this.textBox2.Text.Trim().ToString();
if (i >= 2)
{

url = url.Substring(0, url.LastIndexOf(".")).ToString() + "_" + i + ".html";
}

HtmlAgilityPack.HtmlDocument htmlDocument = htmlWeb.Load(url);
//if (htmlDocument.DocumentNode.InnerText.Contains("未找到")) return;

*[@id="big-pic"]

HtmlNodeCollection nodes = null;
if (url.Contains("https://www.mntup.com"))
{
title = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='title']").InnerText;
nodes = htmlDocument.DocumentNode.SelectNodes("//img");
}
else if (url.StartsWith("http://www.mmonly.cc", StringComparison.OrdinalIgnoreCase))
{
title = htmlDocument.DocumentNode.SelectSingleNode("//h1").InnerText.Substring(0, htmlDocument.DocumentNode.SelectSingleNode("//h1").InnerText.Length - 5);
nodes = htmlDocument.DocumentNode.SelectNodes("//div[@id='big-pic']//img");


}
else
{

title = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='title']")?.InnerText;
nodes = htmlDocument.DocumentNode.SelectNodes("//img");

}
bool flag2 = nodes == null || nodes.Count <= 0;

if (flag2)
{
MessageBox.Show($@"当前页{i}未找到图片,或没有第{i}页");
ImgList.Clear();
textBox1.Clear();
return;
}
int index = this.textBox2.Text.Trim().IndexOf(".com");
string urls = this.textBox2.Text.Trim().ToString().Substring(0, 21);
foreach (HtmlNode item in nodes)
{
//https://www.mntup.com/YouMi/zhangyumeng_38bebee5.html
string houzui = item.Attributes["src"]?.Value;
if (string.IsNullOrEmpty(houzui)) continue;
houzui = houzui.Substring(houzui.LastIndexOf("."), 4);
if (houzui != ".jpg")
{
continue;
};
string imgurl = "";
if (!item.Attributes["src"].Value.StartsWith("http") &&
!item.Attributes["src"].Value.StartsWith("https"))
{


imgurl = urls + item.Attributes["src"].Value;
}
else
{
imgurl = item.Attributes["src"].Value;
}
this.textBox1.AppendText(imgurl + "\r\n");
this.ImgList.Add(imgurl);

}
}

//ImgList = ImgList.Distinct().ToList();
this._totalFile = ImgList.Count;
this.textBox1.AppendText("总共获取图片" + ImgList.Count);

 


}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
/// <summary>
/// 文件下载时事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
//https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E8%90%9D%E8%8E%89&oq=%E8%90%9D%E8%8E%89&rsp=-1
_loadFile++;

int percent = (int)(100.0 * _loadFile / _totalFile);

this.Invoke(new MethodInvoker(delegate
{
this.progressBar1.Value = percent;
this.label1.Text = string.Format("已完成文件下载{0}% {1}/{2}(文件个数)"
, percent
, _loadFile
, _totalFile);
}));
this.textBox1.Invoke(new Action(() =>
{
textBox1.AppendText($"正在下载第{_loadFile}张......\r\n");

}));


if (sender is WebClient)
{
((WebClient)sender).CancelAsync();
((WebClient)sender).Dispose();


}
if (percent == 100)
{

this.textBox1.Invoke(new Action(() =>
{
this.textBox1.AppendText("下载完毕");
}));

}
}
}

转载于:https://www.cnblogs.com/MyZhou/p/11170956.html

这篇关于利用HtmlAgilityPack插件写的一个抓取指定网页的图片 第一次写 很乱 随便看看就行...的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/ajtxey4840/article/details/101178550
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/359659

相关文章

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

CSS Padding 和 Margin 区别全解析

《CSSPadding和Margin区别全解析》CSS中的padding和margin是两个非常基础且重要的属性,它们用于控制元素周围的空白区域,本文将详细介绍padding和... 目录css Padding 和 Margin 全解析1. Padding: 内边距2. Margin: 外边距3. Padd

CSS will-change 属性示例详解

《CSSwill-change属性示例详解》will-change是一个CSS属性,用于告诉浏览器某个元素在未来可能会发生哪些变化,本文给大家介绍CSSwill-change属性详解,感... will-change 是一个 css 属性,用于告诉浏览器某个元素在未来可能会发生哪些变化。这可以帮助浏览器优化

CSS去除a标签的下划线的几种方法

《CSS去除a标签的下划线的几种方法》本文给大家分享在CSS中,去除a标签(超链接)的下划线的几种方法,本文给大家介绍的非常详细,感兴趣的朋友一起看看吧... 在 css 中,去除a标签(超链接)的下划线主要有以下几种方法:使用text-decoration属性通用选择器设置:使用a标签选择器,将tex

前端高级CSS用法示例详解

《前端高级CSS用法示例详解》在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交互和动态效果的关键技术之一,随着前端技术的不断发展,CSS的用法也日益丰富和高级,本文将深... 前端高级css用法在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交