如何在 WebBrowser 控件中使用 XPath?

How to using XPath in WebBrowser Control?

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

但是使用下面的代码,vResult的返回值总是NULL。

        bool completed = false;
        WebBrowser wb = new WebBrowser();
        wb.ScriptErrorsSuppressed = true;
        wb.DocumentCompleted += delegate { completed = true; };
        wb.Navigate("http://whosebug.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://whosebug.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 and download the wgxpath.install.js