asp.net使用WebBrowser採集加載完畢後的頁面(線程安全)

工具類代碼:(代碼可以自己整理下,這裏重點在實現方式)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Windows.Forms;

/// <summary>
/// Summary description for CustomBrowser
/// </summary>
public class CustomBrowser
{
    public CustomBrowser()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    protected string _url;
    string html = "";
    public string GetWebpage(string url)
    {
        _url = url;
        // WebBrowser is an ActiveX control that must be run in a
        // single-threaded apartment so create a thread to create the
        // control and generate the thumbnail
        Thread thread = new Thread(new ThreadStart(GetWebPageWorker));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        string s = html;
        return s;
    }
    protected void GetWebPageWorker()
    {
        var browser = new WebBrowser
        {
            ScrollBarsEnabled = false,
            ScriptErrorsSuppressed = true
        };
        browser.BringToFront(); 
        html = NavigateAndWaitForLoad(browser, new Uri(_url), 0);
    }

    private string NavigateAndWaitForLoad(WebBrowser browser, Uri uri, int waitTime)
    {
        const int sleepTimeMiliseconds = 5000;

        browser.Navigate(uri);
        var count = 0;

        while (browser.ReadyState != WebBrowserReadyState.Complete)
        {
            Thread.Sleep(sleepTimeMiliseconds);
            Application.DoEvents();
            count++;

            if (count > waitTime / sleepTimeMiliseconds)
            {
                break;
            }
        }

        while (browser.Document.Body == null)
        {
            Application.DoEvents();
        }

        return browser.Document.Body.OuterHtml.ToString();
    }
}

 

調用方法:

new CustomBrowser().GetWebpage("http://www.baidu.com");

 

參考鏈接:https://stackoverflow.com/questions/10313369/taking-screenshot-of-an-iframe-on-button-click/10315397#10315397

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章