string htmlstr = string.Empty;
[STAThread]
public string GetHtmlByWeb(string url)
{
try
{ RunWithSingleThread(url);
DateTime dtime = DateTime.Now;
double timespan = ;
//等待 页面加载完毕 并获取到参数
while (string.IsNullOrWhiteSpace(htmlstr) && timespan < )
{
DateTime time2 = DateTime.Now;
timespan = (time2 - dtime).TotalSeconds;
}
// double lo = DateTime.Now.Subtract(dtime).TotalSeconds;
}
catch (Exception)
{ }
finally
{
if (t != null && t.ThreadState == ThreadState.Running)
{
t.Abort();
}
} return htmlstr;
} //线程
private Thread t;
//异步执行WebBrowser
public void RunWithSingleThread(object url)
{
ParameterizedThreadStart ps = new ParameterizedThreadStart(GetHtmlWithBrowser);
t = new Thread(ps);
t.IsBackground = true;
t.ApartmentState = ApartmentState.STA;
t.Start(url);
} private WebBrowser wb;
private void GetHtmlWithBrowser(object url)
{
htmlstr = string.Empty; wb = new WebBrowser();
wb.ScriptErrorsSuppressed = true; //防止脚本异常跳出弹窗
wb.ScrollBarsEnabled = true;
wb.Navigate(url.ToString()); wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
while (wb.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉则可能无法触发 DocumentCompleted 事件。
} }
//获取内容
public void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
htmlstr = wb.Document.Body.InnerHtml; }