且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 WebBrowser 控件中使用 XPath?

更新时间:2023-02-08 15:11:12

我找到了解决方案,代码如下:

I have found solution, here is the code:

    bool completed = false;
    WebBrowser wb = new WebBrowser();
    wb.ScriptErrorsSuppressed = true;
    wb.DocumentCompleted += delegate { completed = true; };
    wb.Navigate("http://***.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