我正在尝试为以下(原型)方法编写实现:
var result = browser.GetHtml(string url);
我需要这个的原因是因为有许多页面将一堆 Javascript 推送到浏览器,然后 Javascript 呈现页面。可靠地检索此类页面的唯一方法是允许 Javascript 在检索结果 HTML 之前在浏览器环境中执行。
我目前的尝试是使用 CefGlue。下载此项目并将其与此答案中的代码相结合后,我想出了以下代码(为了完整性而包含在此处):
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xilium.CefGlue;
namespace OffScreenCefGlue
{
internal class Program
{
private static void Main(string[] args)
{
// Load CEF. This checks for the correct CEF version.
CefRuntime.Load();
// Start the secondary CEF process.
var cefMainArgs = new CefMainArgs(new string[0]);
var cefApp = new DemoCefApp();
// This is where the code path divereges for child processes.
if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp) != -1)
{
Console.Error.WriteLine("CefRuntime could not create the secondary process.");
}
// Settings for all of CEF (e.g. process management and control).
var cefSettings = new CefSettings
{
SingleProcess = false,
MultiThreadedMessageLoop = true
};
// Start the browser process (a child process).
CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp);
// Instruct CEF to not render to a window at all.
CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
cefWindowInfo.SetAsOffScreen(IntPtr.Zero);
// Settings for the browser window itself (e.g. should JavaScript be enabled?).
var cefBrowserSettings = new CefBrowserSettings();
// Initialize some the cust interactions with the browser process.
// The browser window will be 1280 x 720 (pixels).
var cefClient = new DemoCefClient(1280, 720);
// Start up the browser instance.
string url = "http://www.reddit.com/";
CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, url);
// Hang, to let the browser do its work.
Console.Read();
// Clean up CEF.
CefRuntime.Shutdown();
}
}
internal class DemoCefApp : CefApp
{
}
internal class DemoCefClient : CefClient
{
private readonly DemoCefLoadHandler _loadHandler;
private readonly DemoCefRenderHandler _renderHandler;
public DemoCefClient(int windowWidth, int windowHeight)
{
_renderHandler = new DemoCefRenderHandler(windowWidth, windowHeight);
_loadHandler = new DemoCefLoadHandler();
}
protected override CefRenderHandler GetRenderHandler()
{
return _renderHandler;
}
protected override CefLoadHandler GetLoadHandler()
{
return _loadHandler;
}
}
internal class DemoCefLoadHandler : CefLoadHandler
{
public string Html { get; private set; }
protected override void OnLoadStart(CefBrowser browser, CefFrame frame)
{
// A single CefBrowser instance can handle multiple requests
// for a single URL if there are frames (i.e. <FRAME>, <IFRAME>).
if (frame.IsMain)
{
Console.WriteLine("START: {0}", browser.GetMainFrame().Url);
}
}
protected override async void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
{
if (frame.IsMain)
{
Html = await browser.GetSourceAsync();
Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
}
}
}
internal class DemoCefRenderHandler : CefRenderHandler
{
private readonly int _windowHeight;
private readonly int _windowWidth;
public DemoCefRenderHandler(int windowWidth, int windowHeight)
{
_windowWidth = windowWidth;
_windowHeight = windowHeight;
}
protected override bool GetRootScreenRect(CefBrowser browser, ref CefRectangle rect)
{
return GetViewRect(browser, ref rect);
}
protected override bool GetScreenPoint(CefBrowser browser, int viewX, int viewY, ref int screenX, ref int screenY)
{
screenX = viewX;
screenY = viewY;
return true;
}
protected override bool GetViewRect(CefBrowser browser, ref CefRectangle rect)
{
rect.X = 0;
rect.Y = 0;
rect.Width = _windowWidth;
rect.Height = _windowHeight;
return true;
}
protected override bool GetScreenInfo(CefBrowser browser, CefScreenInfo screenInfo)
{
return false;
}
protected override void OnPopupSize(CefBrowser browser, CefRectangle rect)
{
}
protected override void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr buffer, int width, int height)
{
// Save the provided buffer (a bitmap image) as a PNG.
var bitmap = new Bitmap(width, height, width*4, PixelFormat.Format32bppRgb, buffer);
bitmap.Save("LastOnPaint.png", ImageFormat.Png);
}
protected override void OnCursorChange(CefBrowser browser, IntPtr cursorHandle)
{
}
protected override void OnScrollOffsetChanged(CefBrowser browser)
{
}
}
public class TaskStringVisitor : CefStringVisitor
{
private readonly TaskCompletionSource<string> taskCompletionSource;
public TaskStringVisitor()
{
taskCompletionSource = new TaskCompletionSource<string>();
}
protected override void Visit(string value)
{
taskCompletionSource.SetResult(value);
}
public Task<string> Task
{
get { return taskCompletionSource.Task; }
}
}
public static class CEFExtensions
{
public static Task<string> GetSourceAsync(this CefBrowser browser)
{
TaskStringVisitor taskStringVisitor = new TaskStringVisitor();
browser.GetMainFrame().GetSource(taskStringVisitor);
return taskStringVisitor.Task;
}
}
}
相关的代码在这里:
protected override async void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
{
if (frame.IsMain)
{
Html = await browser.GetSourceAsync();
Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
}
}
这实际上似乎有效;您可以使用调试器检查 Html 变量,那里有一个 HTML 页面。问题是,Html 变量在那个回调方法中对我没有好处;它在类层次结构中深埋了三层,我需要在我尝试编写的方法中返回它而不创建 Schroedinbug。
(尝试从该string Html
属性中获取结果,包括尝试在调试器中使用 Html 可视化工具查看它,似乎会导致死锁,这是我非常想避免的,尤其是因为此代码将在服务器上运行) .
var result = browser.GetHtml(string url);
如何安全可靠地实现我的目标?
额外的问题:上述代码中的回调机制是否可以使用这种技术转换为任务?那会是什么样子?