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



http://www.chinasem.cn/article/359659

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

CnPlugin是PL/SQL Developer工具插件使用教程

《CnPlugin是PL/SQLDeveloper工具插件使用教程》:本文主要介绍CnPlugin是PL/SQLDeveloper工具插件使用教程,具有很好的参考价值,希望对大家有所帮助,如有错... 目录PL/SQL Developer工具插件使用安装拷贝文件配置总结PL/SQL Developer工具插

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意