【问题标题】:How to get access to the <HEAD> element of a HTML document using a webbrower control in WinForms?如何使用 WinForms 中的 webbrowser 控件访问 HTML 文档的 <HEAD> 元素?
【发布时间】:2012-01-15 00:11:13
【问题描述】:

我正在使用 WinForms C# 3.5 WebBrowser

我正在尝试访问以下 HTML 文档中的 head 元素:

this.webBrowserTest.DocumentText = @”<html>
    <head>
        <title>Test JavaScript WinForms</title> 
        <meta name="description" content="Test WinForms" />        
    </head>
    <body></body>
</html>”

HtmlElementCollection headCollection = webBrowserTest.Document.GetElementsByTagName("HEAD");
HtmlElement head = headCollection[0]

headCollection[0] 被传递为null

有人知道怎么回事吗?

谢谢

【问题讨论】:

  • 您是否等到 DocumentCompleted?设置 DocumentText 会导致当前文档被转储,并且在异步导航完成对新文档的解析之前,文档将不可用。

标签: c# .net html winforms webbrowser-control


【解决方案1】:

你试过了吗

webBrowserTest.Document.All["HEAD"]; // or head

【讨论】:

  • 感谢 abatishchev。请看我上面对 Petr 的评论——“webBrowserTest.Document.All”的计数为零。
  • @hungoverbunny:改用WebBrowser.Document.Write() 方法。
【解决方案2】:

如果您要为 head 元素提供 id="headid" 属性,您可以使用 webBrowserTest.Document.All["headid"]。

【讨论】:

  • 谢谢彼得,但恐怕这也行不通。我看到“webBrowserTest.Document.All”属性的计数为零。任何其他建议。
  • 这很奇怪。以下对我有用:private void Form1_Load(object sender, EventArgs e) { webBrowser1.DocumentText=@"&lt;html&gt; &lt;head id=""headid""&gt; &lt;title&gt;Test JavaScript WinForms&lt;/title&gt; &lt;meta name=""description"" content=""Test WinForms"" /&gt; &lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt;"; } private void button1_Click(object sender, EventArgs e) { textBox1.Text = webBrowser1.Document.All["headid"].OuterHtml; }
【解决方案3】:

您获取head 标记的代码看起来不错。在访问文档之前,请确保文档已完全加载。您可以通过执行以下操作来完成此操作:

// Add a handler for load complete.
webBrowserTest.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentLoadCompleted);

// Wait until load completes.
while (webBrowserTest.ReadyState != WebBrowserReadyState.Complete)
{
    System.Windows.Forms.Application.DoEvents();
}

// On load complete, do stuff.
private void DocumentLoadCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser browser = sender as WebBrowser;
    HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
    // do stuff...
}

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2013-09-30
    • 2015-01-30
    相关资源
    最近更新 更多