一、添加引用
在解決方案上單擊右鍵,選擇“Add Reference...”,添加“System.Windows.Forms”,添加完後,Web.Config 中應該有類似下面的內容:
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
二、 設定 STA 模式
在 @ Page 指令中加上 AspCompat="true",以強制該網頁在 STA(單一執行緒 Apartment) 模式下執行。結果類似如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" AspCompat="true" %>
三、寫代碼
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
public partial class _Default : System.Web.UI.Page
{
private WebBrowser _webBrowser;
protected void Page_Load(object sender, EventArgs e)
{
string url = Request.QueryString["url"];
if (string.IsNullOrEmpty(url))
{
url = "http://www.cftea.com/";
}
_webBrowser = new WebBrowser();
_webBrowser.ScrollBarsEnabled = false; //不顯示捲軸
_webBrowser.Navigate(url);
_webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Completed);
while (_webBrowser.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉則可能無法觸發 DocumentCompleted 事件。
}
}
public void Completed(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//設定瀏覽器寬度、高度為文檔寬度、高度,以便截取整個網頁。
_webBrowser.Width = _webBrowser.Document.Body.ScrollRectangle.Width;
_webBrowser.Height = _webBrowser.Document.Body.ScrollRectangle.Height;
using (Bitmap bmp = new Bitmap(_webBrowser.Width, _webBrowser.Height))
{
_webBrowser.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("C:\\Capture.png", ImageFormat.Png);
}
}
}
四、說明
在調試時,若出錯,應該停止 ASP.NET Development Server,重新運行,如果你用的是 IIS,可能需要重新啟動 IIS(猜測是這樣),否則 Navigate 那句會出錯。
有些網站抓下來是空白,還沒有仔細研究過為什麼。