public partial class Form1 : Form { /// <summary> /// 存放圖片地址 /// </summary> List<string> ImgList = new List<string>(); /// <summary> /// 當前下載文件 /// </ ...
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("下載完畢");
}));
}
}
}