如何在WebBrowser控件中使用XPath?

时间:2015-01-18 11:19:59

标签: javascript c# xpath webbrowser-control evaluate

在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

2 个答案:

答案 0 :(得分:1)

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

    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

答案 1 :(得分:-2)

Javascript无法在WebBrowser上运行。如果你想要Javascript功能,请使用PhantomJS / Selenium。