首先,由于我缺乏技术知识和可能的错误沟通而道歉,我对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();
}
Run Code Online (Sandbox Code Playgroud)
但是,某些页面(只有少数几个)导致进程挂起.它不是所有的时间,而是经常.我发现问题似乎出现在以下代码部分:
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
Run Code Online (Sandbox Code Playgroud)
看起来web.ReadyState被卡在'interactive'中并且永远不会进展到'complete'所以它只是保持循环.
如果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();
Run Code Online (Sandbox Code Playgroud)
我已经测试了几次,所有页面看起来都很好.我会继续测试以防万一,但如果你有任何关于它可能引起的问题的信息,请告诉我,因为我自己可能找不到它们.
| 归档时间: |
|
| 查看次数: |
10069 次 |
| 最近记录: |