2012-07-17 263 views
8

我試圖捕獲整個瀏覽器屏幕(例如任何工具欄,面板等)的屏幕截圖,不僅整個頁面,所以我得到了這個代碼:從Selenium webdriver的當前窗口獲取窗口句柄(IntPtr)GUID

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"); 
} 

回答

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); 
     // ... 
    } 
} 

當然,這假設你有特定標題單個瀏覽器實例。

+0

好的技巧,順便說一句,但如果有兩個不同具有相同標題的FireFox實例? – kseen 2012-07-20 10:47:22

+0

@kseen您可以用['SingleOrDefault']替換['FirstOrDefault'](http://msdn.microsoft.com/zh-cn/library/bb549039)(http://msdn.microsoft.com/zh-cn//library/bb549274),這樣如果有兩個具有相同標題的瀏覽器實例,則會得到一個異常。如果你在測試案例中,你可以斷言它。 – 2012-07-20 11:29:30

+0

@PaoloMoretti我怎樣才能得到當前窗口(手動打開的現有窗口),這是不是由驅動程序打開意味着我無法使用driver.getWindowHandle(); – 2015-10-10 09:21:46

2

只是和黑客的想法。你可以使用Reflection方法來獲取firefox實例的進程。首先聲明從FirefoxDriver繼承FirefoxDriverEx類 - 訪問受保護的二進制屬性,它封裝流程實例:

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); 
       // ... 
      } 
     } 
+0

您能否在FireFox瀏覽器中添加另外一種查找窗口的方法,例如IE,Chrome,Safari在Selenium中?問題是我找不到'ChromeBinary'或者其他像'FireFoxBinary'的東西。 – kseen 2012-08-09 19:12:52

+0

此方法不適用於IE或Chrome,因爲在這些情況下,瀏覽器的進程由外部硒服務控制,例如IEDriverServer.exe和chromedriver.exe。這種方法只是黑客和'按原樣'工作。對於查找工作方法,您可以查看硒驅動程序的來源,並可能構建自己的版本。 – necrostaz 2012-08-10 09:20:58

+0

所以,只有一個robuts方法存在用於獲取瀏覽器窗口的句柄,這是通過部分窗口標題找到使用WinAPI的窗口? – kseen 2012-08-10 13:41:27

0

開箱即用,硒不暴露驅動程序進程ID或瀏覽器HWND,但它是可能的。 下面是獲得HWND

  • 當驅動程序初始化,得到中心的網址,並提取端口號
  • 從端口號,發現其正在使用此端口進行監聽,即進程ID的邏輯。驅動程序的PID
  • 導航後,從iexplore的所有實例中查找父PID與驅動程序的pid匹配,即瀏覽器pid。
  • 獲取瀏覽器pid的Hwnd 一旦找到瀏覽器hwnd,您可以使用win32 API將硒帶到前臺。

它不可能在這裏發佈完整的代碼,完整的工作液(C#),使瀏覽器在前面我的博客上

http://www.pixytech.com/rajnish/2016/09/selenium-webdriver-get-browser-hwnd/