c# - 正文加载事件执行后在 WinForms WebBrowser 中获取 HTML 正文内容

标签 c# html winforms webbrowser-control onload

我在 WinForms 中有一个 WebBrowser 控件,其 URL 属性设置为外部网页。我还有一个 DocumentCompleted 事件的事件处理程序。在此处理程序中,我试图获取特定元素,但 wb.Document.Body 似乎在执行 onload 之前捕获了 HTML。

{System.Windows.Forms.HtmlElement}
    All: {System.Windows.Forms.HtmlElementCollection}
    CanHaveChildren: true
    Children: {System.Windows.Forms.HtmlElementCollection}
    ClientRectangle: {X = 0 Y = 0 Width = 1200 Height = 0}
    Document: {System.Windows.Forms.HtmlDocument}
    DomElement: {mshtml.HTMLBodyClass}
    ElementShim: {System.Windows.Forms.HtmlElement.HtmlElementShim}
    Enabled: true
    FirstChild: null
    htmlElement: {mshtml.HTMLBodyClass}
    Id: null
    InnerHtml: "\n"
    InnerText: null
    Name: ""
    NativeHtmlElement: {mshtml.HTMLBodyClass}
    NextSibling: null
    OffsetParent: null
    OffsetRectangle: {X = 0 Y = 0 Width = 1200 Height = 0}
    OuterHtml: "<body onload=\"evt_Login_onload(event);\" uitheme=\"Web\">\n</body>"
    OuterText: null
    Parent: {System.Windows.Forms.HtmlElement}
    ScrollLeft: 0
    ScrollRectangle: {X = 0 Y = 0 Width = 1200 Height = 0}
    ScrollTop: 0
    shimManager: {System.Windows.Forms.HtmlShimManager}
    ShimManager: {System.Windows.Forms.HtmlShimManager}
    Style: null
    TabIndex: 0
    TagName: "BODY"

"<body onload=\"evt_Login_onload(event);\" uitheme=\"Web\">\n</body>"是 JavaScript 之前的内容。有没有办法在evt_Login_onload(event);之后捕获body标签的状态?执行?

我也尝试过使用 wb.Document.GetElementById("id") , 但它返回 null。

最佳答案

这是如何完成的,我在行内添加了一些评论:

private void Form1_Load(object sender, EventArgs e)
{
    bool complete = false;
    this.webBrowser1.DocumentCompleted += delegate
    {
        if (complete)
            return;
        complete = true;
        // DocumentCompleted is fired before window.onload and body.onload
        this.webBrowser1.Document.Window.AttachEventHandler("onload", delegate
        {
            // Defer this to make sure all possible onload event handlers got fired
            System.Threading.SynchronizationContext.Current.Post(delegate 
            {
                // try webBrowser1.Document.GetElementById("id") here
                MessageBox.Show("window.onload was fired, can access DOM!");
            }, null);
        });
    };

    this.webBrowser1.Navigate("http://www.example.com");
}

已更新,现在是 2019 年了,这个答案令人惊讶地仍然受到关注,所以我想指出,我推荐的使用现代 C# 的方法是使用 async/await,例如this .

关于c# - 正文加载事件执行后在 WinForms WebBrowser 中获取 HTML 正文内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368778/

相关文章:

c# - 创建窗口句柄时出错

c# - 使用 PdfSharp-WP7 在 wp8 中读取和写入带有一些图像的 pdf 文件

c# - Synthesizer.Speak 上的应用程序退出 - System.Speech.dll - 非 Microsoft 语音

c# - 如何在 xamarin iOS 中更新 sqlite 数据库表

c# - WPF MVVM 绑定(bind)问题/疑问

css - 对齐 botton div,在未嵌套的顶部 div 之上,其中底部 div 的 z-index 为 :1;

html - colspan + 固定宽度内容影响td宽度

c# - 绘制/绘制外部形式

php - 数组循环问题

c# - 这些功能中哪一个更有效?