我正在尝试捕获整个浏览器屏幕的截图(例如,使用任何工具栏,面板等),而不仅仅是整个页面,所以我有这个代码:
using (FirefoxDriver driver = new FirefoxDriver())
{
driver.Navigate().GoToUrl(url);
ScreenCapture sc = new ScreenCapture();
// How can I find natural IntPtr handle of window here, using GUID-like identifier returning by driver.currentWindowHandle?
Image img = sc.CaptureWindow(...);
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
return new FileStreamResult(ms, "image/jpeg");
}
答案 0 :(得分:3)
您可以使用Process.GetProcesses
获取窗口句柄:
using (FirefoxDriver driver = new FirefoxDriver())
{
driver.Navigate().GoToUrl(url);
string title = String.Format("{0} - Mozilla Firefox", driver.Title);
var process = Process.GetProcesses()
.FirstOrDefault(x => x.MainWindowTitle == title);
if (process != null)
{
var screenCapture = new ScreenCapture();
var image = screenCapture.CaptureWindow(process.MainWindowHandle);
// ...
}
}
这当然假设您有一个具有该特定标题的浏览器实例。
答案 1 :(得分:2)
只是想法黑客。您可以使用Reflection方法来获取firefox实例的进程。首先声明从FirefoxDriver继承的FirefoxDriverEx类 - 访问封装了Process实例的受保护的Binary属性:
class FirefoxDriverEx : FirefoxDriver {
public Process GetFirefoxProcess() {
var fi = typeof(FirefoxBinary).GetField("process", BindingFlags.NonPublic | BindingFlags.Instance);
return fi.GetValue(this.Binary) as Process;
}
}
您可能获得访问MainWindowHandle属性的流程实例
using (var driver = new FirefoxDriverEx()) {
driver.Navigate().GoToUrl(url);
var process = driver.GetFirefoxProcess();
if (process != null) {
var screenCapture = new ScreenCapture();
var image = screenCapture.CaptureWindow(process.MainWindowHandle);
// ...
}
}
答案 2 :(得分:1)
开箱即用,selenium不会公开驱动程序进程ID或浏览器hwnd,但它是可能的。 以下是获取hwnd的逻辑
无法在此处发布完整代码,将浏览器放在我面前的完整工作解决方案(C#)
http://www.pixytech.com/rajnish/2016/09/selenium-webdriver-get-browser-hwnd/