Web.ReadyState未达到';完成';阶段
本文关键字:阶段 完成 ReadyState 未达到 Web | 更新日期: 2023-09-27 18:20:40
首先为我缺乏技术知识和可能的沟通失误道歉,我是C#的新手。
我接手了一个项目,该项目抓取了许多网页并将其保存为.png文件。
private void CaptureWebPage(string URL, string filePath, ImageFormat format)
{
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
web.ScrollBarsEnabled = false;
web.ScriptErrorsSuppressed = true;
web.Navigate(URL);
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(5000);
int width = web.Document.Body.ScrollRectangle.Width;
width += width / 10;
width = width <= 300 ? 600 : width;
int height = web.Document.Body.ScrollRectangle.Height;
height += height / 10;
web.Width = width;
web.Height = height;
_bmp = new System.Drawing.Bitmap(width, height);
web.DrawToBitmap(_bmp, new System.Drawing.Rectangle(0, 0, width, height));
_bmp.Save(filePath, format);
_bmp.Dispose();
}
但是,有些页面(只有少数页面)会导致进程挂起。这不是所有的时间,但相当经常。我发现问题似乎出现在代码的以下部分:
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
它看起来像是一张网。ReadyState一直停留在"交互式",从未进展到"完成",所以它只是保持循环。
如果是web,是否可以放入导致该页面的进程重新启动的代码。ReadyState="Interactive"一段时间,如果是,语法会是什么?
我用以下代码替换了现有的有问题的代码(可以在thebotnet.com上找到):
while (web.IsBusy)
System.Windows.Forms.Application.DoEvents();
for (int i = 0; i < 500; i++)
if (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
else
break;
System.Windows.Forms.Application.DoEvents();
我测试了几次,所有的页面似乎都刮得很好。我会继续测试它以防万一,但如果你有任何关于它可能导致的问题的信息,请告诉我,因为我自己可能找不到。
VB.NET代码:
While WebBrowser1.IsBusy
System.Windows.Forms.Application.DoEvents()
End While
For i As Integer = 0 To 499
If WebBrowser1.ReadyState <> System.Windows.Forms.WebBrowserReadyState.Complete Then
System.Windows.Forms.Application.DoEvents()
System.Threading.Thread.Sleep(10)
Else
Exit For
End If
Next
System.Windows.Forms.Application.DoEvents()