2014-03-19 77 views
0

我創建了幾個使用Selenium Webdriver的Powershell腳本。在Powershell中使用JavascriptExecutor

現在我需要給其中的一個添加一些Javascript功能,但是我無法弄清楚我如何獲得正確的語法。

嘗試下面的C#代碼從這個討論轉換: Execute JavaScript using Selenium WebDriver in C#

這是我的代碼看起來像此刻:

# Specify path to Selenium drivers 
$DriverPath = (get-item ".\").parent.parent.FullName + "\seleniumdriver\" 
$files = Get-ChildItem "$DriverPath*.dll" 

# Read in all the Selenium drivers 
foreach ($file in $files) { 
    $FilePath = $DriverPath + $file.Name 
    [Reflection.Assembly]::LoadFile($FilePath) | out-null 
} 

# Create instance of ChromeDriver 
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver 

# Go to example page google.com 
$driver.Url = "http://www.google.com" 

# Create instance of IJavaScriptExecutor 
$js = New-Object IJavaScriptExecutor($driver) 

# Run Javascript to get current url title 
$title = $js.executeScript("return document.title") 

# Write titel to cmd 
write-host $title 

但我不斷地得到創建實例時,下面的錯誤IJavaScriptExecutor:

「New-Object:Can not find type [IJavaScriptExecutor]:確保包含此類型的程序集已加載。」

任何人都可以找出我失蹤的東西嗎?它是不正確的代碼?缺少額外的DLL?

BR, 基督教

回答

1

的問題是,IJavaScriptExecutor是一個接口,你不能創建一個接口的實例。相反,您需要創建一個實現接口的類的實例。在這種情況下,ChromeDriver類將實現此接口,因此您可以跳過創建$js變量的行,而改爲使用$driver

所以你會得到類似下面的,因爲你的JavaScript函數按預期工作:

# Create instance of ChromeDriver 
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver 

# Go to example page google.com 
$driver.Url = "http://www.google.com" 

# Run Javascript to get current url title 
$title = $driver.executeScript("return document.title") 

你可以閱讀更多有關這些類上the Selenium Documentation

+0

因此,我最好仔細閱讀如何使用Powershell實例,接口和類。 但現在你的例子使用$驅動程序來執行JavaScript按預期工作。 謝謝羅伯特,非常感謝! –