首页 技术交流 Winfrom引用CefSharp浏览器ChromiumWebBrowser执行脚本、获取网页HTML代码 正文

Winfrom引用CefSharp浏览器ChromiumWebBrowser执行脚本、获取网页HTML代码

发布日期:2019年11月26日 09:48        阅读次数:1738

我们上篇文章介绍了CefSharp浏览器ChromiumWebBrowser的基本用法,那么如何通过这个浏览器获取网页HTML代码呢,其实CefSharp很好的封装了这个方法,示例代码如下:

private string GetHTMLFromWebBrowser(ChromiumWebBrowser wb)
        {
            // call the ViewSource method which will open up notepad and display the html.
            // this is just so I can compare it to the html returned in GetSourceAsync()
            // This is displaying all the html code (including child frames)
            wb.GetBrowser().MainFrame.ViewSource();

            // Get the html source code from the main Frame.
            // This is displaying only code in the main frame and not any child frames of it.
            Task<String> taskHtml = wb.GetBrowser().MainFrame.GetSourceAsync();

            string response = taskHtml.Result;
            return response;
        }

   如此,我们便能获取到加载的url地址的网页HTML代码了。

另外,有时我们可能需要在加载的时候去执行我们自己的js代码,CefSharp也给我们提供了执行js脚本的方法,用法如下:

  browser1.Load(url);
  browser1.ExecuteScriptAsyncWhenPageLoaded("$('.recommend-pro-anchor a').click();$('.content-sku-right').first().click();$('.article-content-sku').first().click();$('.tpc-item-golink-btn').first().click();", false);

ExecuteScriptAsyncWhenPageLoaded表示在页面加载完成的时候执行js代码,并且通过第二个参数(bool类型)确实是否执行一次还是多次。                               

评论:

共 0 页 0 条记录,当前为第 1 页