【问题标题】:C# WebBrowser control save web page as image, redirect issueC# WebBrowser 控件将网页保存为图像,重定向问题
【发布时间】:2012-02-25 16:05:45
【问题描述】:

我在控制台应用程序中使用 Web 浏览器控件,它是以编程方式创建的。它通过一个 url 并使用 DrawToBitmap 将页面保存为图像文件。

它似乎适用于许多 URL,但不适用于某些 URL,包括 www.google.co.uk,它保存了一个空白页面。 IBM.com 和 microsoft.com 工作,认为这可能与网站进行重定向有关。

这是代码:

 int width = -1;
        int height = -1;

        // Load the webpage into a WebBrowser control
        WebBrowser wb = new WebBrowser();
        wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
        wb.Navigated += new WebBrowserNavigatedEventHandler(wb_Navigated);

        wb.AllowNavigation = true;
        wb.ScrollBarsEnabled = false;
        wb.ScriptErrorsSuppressed = true;
        wb.Navigate(url);

        while (wb.ReadyState != WebBrowserReadyState.Complete)
        {
            Debug.WriteLine("Loading loop..");
            Application.DoEvents();
        }



        // Set the size of the WebBrowser control
        wb.Width = width;
        wb.Height = height;

        if (width == -1)
        {
            // Take Screenshot of the web pages full width
            wb.Width = wb.Document.Body.ScrollRectangle.Width;
        }

        if (height == -1)
        {
            // Take Screenshot of the web pages full height
            wb.Height = wb.Document.Body.ScrollRectangle.Height;
        }

        // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
        Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
        wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
        wb.Dispose();

        bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
        Debug.WriteLine("Saved");
        Application.Exit();

您知道为什么某些网站无法运行吗?

感谢您的宝贵时间

【问题讨论】:

  • www.google.co.uk 不会为所有人重定向。您的测试服务器/工作站在哪里运行,哪个区域设置?您是否使用其他服务器测试过它,包括执行即时 HTTP 位置重定向的 localhost URL?
  • 在英国应该是 .co.uk,.com 也不起作用。将尝试在另一台服务器上进行测试。它可能不是重定向,但它似乎只影响某些网站

标签: asp.net image redirect webbrowser-control


【解决方案1】:

你可能想在加载完成之前保存它,检测WB是否满载是WB控件最大的问题,我多年来开发了几种方法,因此涉及大量工作,并且有是您需要实施的各种方法。

另外,不要忘记,某些 HTML 数据可能会加载到框架中,因此您可能需要获取对框架的引用并对每个框架和这些框架中的所有框架执行相同的操作(嵌套框架无限嵌套必须检测到并添加到您的对象引用中才能使用)- 可靠的加载完整检测还需要帧引用,单独检查 readystate 或 .busy 是非常不可靠的,您的代码几乎肯定会在大多数情况下中断。查看我的一些与 WB 相关的帖子以了解更多信息,或者:Webbrowser Control Limitations

另外,如果您需要更多帮助,请告诉我,我可以为您提供有关检测加载完成的方法的指示。

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多