asp.net採集網頁圖片的具體方法

來源:互聯網
上載者:User

在網上找了下大多都是通過字串操作找出img標籤,這種方式操作起來比較麻煩,而且代碼看起來比較累。這裡我用的方法是通過WebBrowser來載入一個頁面,然後HTMLDocument類來操作省去了字串操作的步驟,直接調用GetElementsByTagName把所有圖片地址返回到一個HtmlElementCollection對象裡。
代碼如下: 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class GatherPic
{
private string savePath;
private string getUrl;
private WebBrowser wb;
private int iImgCount;
//初始化參數
public GatherPic(string sWebUrl, string sSavePath)
{
this.getUrl = sWebUrl;
this.savePath = sSavePath;
}
//開始採集
public bool start()
{
if (getUrl.Trim().Equals(""))
{
MessageBox.Show("哪來的蝦米連網址都沒輸!");
return false;
}
this.wb = new WebBrowser();
this.wb.Navigate(getUrl);
//委託事件
this.wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
return true;
}
//WebBrowser.DocumentCompleted委託事件
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//頁面裡架構iframe載入完成不掉用SearchImgList()
if (e.Url != wb.Document.Url) return;
SearchImgList();
}
//檢查出所有圖片並採集到本地
public void SearchImgList()
{
string sImgUrl;
//取得所有圖片地址
HtmlElementCollection elemColl = this.wb.Document.GetElementsByTagName("img");
this.iImgCount = elemColl.Count;
foreach (HtmlElement elem in elemColl)
{
sImgUrl = elem.GetAttribute("src");
//調用儲存遠程圖片函數
SaveImageFromWeb(sImgUrl, this.savePath);
}
}
//儲存遠程圖片函數
public int SaveImageFromWeb(string imgUrl, string path)
{
string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
path = path + "\\" + imgName;
string defaultType = ".jpg";
string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
foreach (string it in imgTypes)
{
if (imgType.ToLower().Equals(it))
break;
if (it.Equals(".bmp"))
imgType = defaultType;
}
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
request.Timeout = 10000;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
if (response.ContentType.ToLower().StartsWith("image/"))
{
byte[] arrayByte = new byte[1024];
int imgLong = (int)response.ContentLength;
int l = 0;
// CreateDirectory(path);
FileStream fso = new FileStream(path, FileMode.Create);
while (l < imgLong)
{
int i = stream.Read(arrayByte, 0, 1024);
fso.Write(arrayByte, 0, i);
l += i;
}
fso.Close();
stream.Close();
response.Close();
return 1;
}
else
{
return 0;
}
}
catch (WebException)
{
return 0;
}
catch (UriFormatException)
{
return 0;
}
}
}
}
//-----------------調用代碼--------------------
GatherPic gatherpic = new GatherPic(“http://www.baidu.com”,"C:\test");
//請確保c:\下存在test路徑
gatherpic.start()
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.