如何在 Web 浏览器控件中使用 XPath

How to using XPath in WebBrowser Control?

本文关键字:XPath 控件 浏览器 Web      更新时间:2023-09-26

在C# WinForms示例应用程序中,我使用了WebBrowser控件。我想使用 JavaScript XPath 来选择单个节点。为此,我使用 XPathJS

但使用以下代码,vResult 的返回值始终为 NULL。

        bool completed = false;
        WebBrowser wb = new WebBrowser();
        wb.ScriptErrorsSuppressed = true;
        wb.DocumentCompleted += delegate { completed = true; };
        wb.Navigate("http://stackoverflow.com/");
        while (!completed)
        {
            Application.DoEvents();
            Thread.Sleep(100);
        }
        if (wb.Document != null)
        {
            HtmlElement head = wb.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = wb.Document.CreateElement("script");
            mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)scriptEl.DomElement;
            element.src = "https://raw.github.com/andrejpavlovic/xpathjs/master/build/xpathjs.min.js";
            head.AppendChild(scriptEl);
            // Initialize XPathJS
            wb.Document.InvokeScript("XPathJS.bindDomLevel3XPath");
            string xPathQuery = @"count(//script)";
            string code = string.Format("document.evaluate('{0}', document, null, XPathResult.ANY_TYPE, null);", xPathQuery);
            var vResult = wb.Document.InvokeScript("eval", new object[] { code });
        }

有没有办法使用 WebBrowser 控件来执行 JavaScript XPath?

Rem:我想避免使用HTML Agility Pack,我想直接操作WebBrowser控件的DOM的内容mshtml。IHTMLElement

我已经找到了解决方案,这是代码:

    bool completed = false;
    WebBrowser wb = new WebBrowser();
    wb.ScriptErrorsSuppressed = true;
    wb.DocumentCompleted += delegate { completed = true; };
    wb.Navigate("http://stackoverflow.com/");
    while (!completed)
    {
        Application.DoEvents();
        Thread.Sleep(100);
    }
    if (wb.Document != null)
    {
            HtmlElement head = wb.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = wb.Document.CreateElement("script");
            mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)scriptEl.DomElement;
            element.text = System.IO.File.ReadAllText(@"wgxpath.install.js");
            head.AppendChild(scriptEl);
            // Call wgxpath.install() from JavaScript code, which will ensure document.evaluate
            wb.Document.InvokeScript("eval", new object[] { "wgxpath.install()" });
            string xPathQuery = @"count(//script)";
            string code = string.Format("document.evaluate('{0}', document, null, XPathResult.NUMBER_TYPE, null).numberValue;", xPathQuery);
            int iResult = (int) wb.Document.InvokeScript("eval", new object[] { code });
    }

我使用"一个纯粹的JavaScript XPath库":wicked-good-xpath并下载wgxpath.install.js