C# 网页图片采集

http://blog.csdn.net/a237428367/article/details/5987832

 

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 ImageCollect  
  • {  
  •     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;  
  •             }  
  •         }  
  •     }  
  • }  

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 ImageCollect { 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; } } } }  

 

 

调用方法

 

[c-sharp] view plain copy print?
  1. GatherPic g = new GatherPic(“http://www.baidu.com”,"E:/XXX");  
  2.             g.start();  

=====================================================

 

在web项目中使用WebBrowser类-----给网站抓图

 

最近做一个WEB项目,其中要求有个功能就是程序能网页抓图,举个例子: 在test.aspx页面上放一个TextBox和一个Button,TextBox用来输入要抓取的网页地址,然后按了Button之后,服务器要对前面输入的网址进行抓图,然后显示出来。我把抓图的业务逻辑做成一个类:

using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;

/// <summary>
/// WebSnap :网页抓图对象
/// </summary>
public class WebSnap2
{

    public WebSnap2()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 开始一个抓图并返回图象
    /// </summary>
    /// <param name="Url">要抓取的网页地址</param>
    /// <returns></returns>
    public Bitmap StartSnap(string Url)
    {
        WebBrowser myWB = this.GetPage(Url);
        Bitmap returnValue = this.SnapWeb(myWB);
        myWB.Dispose();
        return returnValue;
    }

    private WebBrowser GetPage(string Url)
    {
        WebBrowser myWB = new WebBrowser();
        myWB.ScrollBarsEnabled = false;
        myWB.Navigate(Url);
        while (myWB.ReadyState != WebBrowserReadyState.Complete)
        {
            System.Windows.Forms.Application.DoEvents();
        }
        return myWB;
    }

    private Bitmap SnapWeb(WebBrowser wb)
    {
        HtmlDocument hd = wb.Document;
        int height = Convert.ToInt32(hd.Body.GetAttribute("scrollHeight")) + 10;
        int width = Convert.ToInt32(hd.Body.GetAttribute("scrollWidth")) + 10;
        wb.Height = height;
        wb.Width = width;
        Bitmap bmp = new Bitmap(width, height);
        Rectangle rec = new Rectangle();
        rec.Width = width;
        rec.Height = height;
        wb.DrawToBitmap(bmp, rec);
        return bmp;
    }

}

 

 

然后在test.asp的button_click事件里面调用:

        WebSnap ws = new WebSnap();
        Bitmap bmp= ws.StartSnap(TextBox1.Text);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.BinaryWrite(ms.GetBuffer());

 

转载于:https://www.cnblogs.com/qq260250932/p/5361043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
预览图片见:http://www.cnblogs.com/xxpyeippx/archive/2008/03/31/1131211.html运行环境windows nt/xp/2003 or above.net Framework 1.1SqlServer 2000 开发环境 VS 2003目的学习了网络编程,总要做点什么东西才好。于是想到要做一个网页内容采集器。作者主页: http://www.fltek.com.cn使用方式测试数据采用自cnBlog。见下图用户首先填写“起始网页”,即从哪一页开始采集。然后填写数据库连接字符串,这里是定义了采集到的数据插入到哪个数据库,后面选择表名,不必说了。网页编码,不出意外的话,国大陆都可以采用UTF-8爬取文件名的正则:呵呵 这个工具明显是给编程人员用的。正则都要直接填写啦。比如说cnblogs的都是数字的,所以写了\d建表帮助:用户指定要建立几个varchar型的,几个text型的,主要是放短数据和长数据啊。如果你的表里本来就有列,那就免啦。程序里面没有做验证哦。网页设置里面:采集内容前后标记:比如说都有 xxx,如果我要采集xxx就写“到”,意思,当然就是到之间的内容啦。后面的几个文本框是显示内容的。点击“获取URL”可以查看它捕获的Url对不对的。点击“采集”,可以把采集内容放到数据库,然后就用 Insert xx () (select xx) 可以直接插入目标数据了。程序代码量非常小(也非常简陋),需要的改动一下啦。不足 应用到了正则表达式、网络编程由于是最简单的东西,所以没有用多线程,没有用其他的优化方法,不支持分页。测试了一下,获取38条数据,用了700M内存啊。。。。如果有用的人 ,可以改一下使用啦。方便程序员用,免写很多代码。Surance Yin@ Surance Center 转载请注明出处
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值