c#抓取网页数据(web项目中使用WebBrowser类--给网站抓图最近做一个WEB )

优采云 发布时间: 2021-11-08 23:05

  c#抓取网页数据(web项目中使用WebBrowser类--给网站抓图最近做一个WEB

)

  使用系统;

  调用方法

  GatherPicg=newGatherPic("","E:/XXX"); g.start();

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

  在web项目中使用WebBrowser类-----给网站拍照

  最近做了一个WEB项目,需要一个程序可以抓取网页的功能。例如:在 test.aspx 页面上放置一个 TextBox 和一个 Button。 TextBox用于输入要抓取的网页地址,然后按下Button后,服务器会对之前输入的URL进行截图,然后显示出来。我把截图的业务逻辑做成了一个类:

  using System;

using System.Data;

using System.Windows.Forms;

using System.Drawing;

///

/// WebSnap :网页抓图对象

///

public class WebSnap2

{

public WebSnap2()

{

//

// TODO: 在此处添加构造函数逻辑

//

}

///

/// 开始一个抓图并返回图象

///

/// 要抓取的网页地址

///

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());

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线