1. 程式人生 > >selenium java IE問題 && Firefox問題 && chrome問題

selenium java IE問題 && Firefox問題 && chrome問題

1. Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remoteserver or browser start-up failure.

1、下載一個系統相容的IEDriver,可以從這裡下載(http://code.google.com/p/selenium/downloads/list),我下載了IEDriverServer_Win32_2.31.0.zip
2、解壓,放在目錄下,我放在了IE安裝目錄下(C:\Program Files\Internet Explorer)
3、修改程式碼,System.setProperty("webdriver.ie.driver","C:\\Program Files\\Internet Explorer\\IEDriverServer.exe");

新增IE驅動:

     System.setProperty("webdriver.ie.driver","C:\\Program Files\\Internet Explorer\\IEDriverServer.exe");
     DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
     ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
     webdriver = new InternetExplorerDriver(ieCapabilities);

==================================================================================================================

2.使用ChromeDriver時要使用webdriver.chrome.driver來指定chromeDriver的位置,具體見例項:<單獨下載chromedriver.exe,如問題1:(http://code.google.com/p/selenium/downloads/list)>

Java程式碼 複製程式碼 收藏程式碼
  1. package selenium.test.googleSearch;  
  2. import org.openqa.selenium.WebDriver;  
  3. import org.openqa.selenium.chrome.ChromeDriver;  
  4. publicclass BaiduChromeDriver {  
  5.     /** 
  6.      * @param args 
  7.      */
  8.     publicstaticvoid main(String[] args) {  
  9.         // TODO Auto-generated method stub
  10.     //設定訪問ChromeDriver的路徑
  11. System.setProperty("webdriver.chrome.driver""C:\\Documents and Settings\\Administrator\\Local Settings\\
  12. Application Data\\Google\\Chrome\\Application\\chromedriver.exe");   
  13.         WebDriver driver = new ChromeDriver();  
  14.         driver.get("http://www.baidu.com/");  
  15.     }  
  16. }  
package selenium.test.googleSearch;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BaiduChromeDriver {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	//設定訪問ChromeDriver的路徑
System.setProperty("webdriver.chrome.driver", "C:\\Documents and Settings\\Administrator\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chromedriver.exe"); 
		WebDriver driver = new ChromeDriver();
		driver.get("http://www.baidu.com/");

	}

}


ps:
chrome瀏覽器安裝時預設路徑如下:

OS Expected Location of Chrome
Linux /usr/bin/google-chrome1
Mac /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
Windows XP %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome.exe
Windows Vista C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe


chrome不能夠手動選擇安裝路徑,只能在上述對應的目錄下檢視chrome檔案資訊

******************Chrome****************************************************************************************

Started ChromeDriver
port=17034
version=22.0.1203.0b
log=E:\LICMWork\testmvn\chromedriver.log
[0730/173528:ERROR:automation_proxy.cc(320)] Channel error in AutomationProxy.
Exception in thread "main" org.openqa.selenium.WebDriverException: Chrome did not respond to 'GetChromeDriverAutomationVersion'. Elapsed time was 1 ms. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 12.91 seconds
Build info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39'
System info: host: 'licm', ip: '172.19.41.30', os.name: 'Windows Vista', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_10-rc2'
Driver info: org.openqa.selenium.chrome.ChromeDriver
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
 at java.lang.reflect.Constructor.newInstance(Unknown Source)
 at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
 at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
 at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595)
 at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
 at org.openqa.selenium.chrome.ChromeDriver.startSession(ChromeDriver.java:181)
 at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
 at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:139)
 at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:160)
 at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:149)
 at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:106)
 at Founder.testmvn.BaiduChromeDriver.main(BaiduChromeDriver.java:12)

******************************

chromedriver.exe當前版本為:version: '2.23.1', revision: '17143', time: '2012-06-08 18:59:28',該版本可能不支援當前最新chrome瀏覽器,或存在未修復的bug。

更換為最新版chromedriver.exe(2014/2/6版),重新執行該問題已經解決了。

===================================================================================================================

在Windows下使用FirefoxDriver的怪問題

1. 用FirefoxDriver寫了個測試網頁的程式,在Linux下執行正常,但在Windows下執行出錯,報:Exception in thread "main" org.openqa.selenium.UnsupportedCommandException: Bad request
搞了大半天,用了各種方式嘗試解決,都沒搞定,終於google找到了網上的一個文章關於這個的:http://seleniumforum.forumotion.net/t717-trouble-with-creating-an-firefoxdriver-object

居然通過修改C:\WINDOWS\system32\drivers\etc\HOSTS 檔案,在其中新增上這句:

127.0.0.1 localhost

程式碼: import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class WebTest{ private WebDriver webdriver; private String url; @Before public void setUp() throws Exception { webdriver =  new FirefoxDriver(); url = "http://www.baidu.com"; webdriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @After public void tearDown() throws Exception { webdriver.quit(); } @Test public void testWebTest() throws Exception  { webdriver.get(url+"/"); WebElement element = webdriver.findElement(By.id("kw")); element.clear(); element.sendKeys("test"); WebElement submitElement = webdriver.findElement(By.id("su")); submitElement.click(); } }
=============================================================================
錯誤提醒:http://my.oschina.net/dyhunter/blog/94090

1)Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.
出現這個錯誤,是說明你的 FireFox 檔案並沒有安裝在預設目錄下,這時候需要在最開始執行:System.setProperty 設定環境變數  "webdriver.firefox.bin" 將自己機器上 FireFox 的正確路徑設定完畢後即可。
2)Exception in thread "main" org.openqa.selenium.UnsupportedCommandException: Bad request

出現這個錯誤,很有意思。 查了一下 有人說應該是 hosts 出現了問題,加上一個 127.0.0.1  localhost 就行了,但我的 hosts 上肯定有這個玩意,為啥也會出現這個問題呢? 

經過除錯,發現 127.0.0.1 localhost 的設定必須要在 hosts 檔案的最開始,而且如果後面有其他設定後,也不要再出現同樣的 127.0.0.1 localhost ,只要有就會出錯。(因為我為了方便訪問 google 的網站,專門加入了 smarthosts 的內容,導致了 localhost 的重複)

【3. 測試 Chrome】
Chrome 雖然不是 Selenium 的原配,但是沒辦法,她太火辣了,絕對不能拋下她不管的。
把 ExampleForFireFox.java 稍微修改就可以製作出一個 ExampleForChrome.java ,直接把 new FireFoxDriver() 修改為 new ChromeDriver() 你會發現還是行不通。

錯誤如下:
1)Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
這應該是找不到 chrome 的檔案,好吧,利用 System.setProperty 方法新增路徑,這裡要注意,是 “webdriver.chrome.driver” 可不是“webdriver.chrome.bin

設定路徑後還是會報錯:
2)[6416:4580:1204/173852:ERROR:gpu_info_collector_win.cc(91)] Can't retrieve a valid WinSAT assessment.
這個貌似是因為 Selenium 無法直接啟動 Chrome 導致的,必須要通過前面咱們下載 Chrome 的第三方外掛 ChromeDriver,去看第一個錯誤中提示給你的 網址:http://code.google.com/p/selenium/wiki/ChromeDriver
按照人家給的例子來修改我們的測試程式碼吧:

=============================================================================

2. Exception in thread "main" org.openqa.selenium.WebDriverException: Unable to bind to locking port 7054 within 45000 ms
Build info: version: '2.14.0', revision: '14955', time: '2011-11-29 11:43:45'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_16'
Driver info: driver.version: FirefoxDriver
 at org.openqa.selenium.internal.SocketLock.lock(SocketLock.java:95)


解決方案:

selenium-server-standalone-2.33.0.jar

selenium-2.33.0.zip

選擇最新的 jar 版本~重新加到工程裡面~

===============================================================================================

FireFox瀏覽器可以直接使用下列程式碼就能開啟。

WebDriver driver = new FirefoxDriver();
       driver.get("http://www.google.com.hk");

*************************************************************************************

IE需要設定,不然會提示錯誤。如果提示一下問題,請參照~~

1. 開啟IE瀏覽器的程式碼如下:

public class FirstExampe {
       public static void main(String[] args) {

 System.setProperty("webdriver.ie.driver","C:\\Users\\li.chunmei\\Downloads\\IEDriverServer_Win32_2.33.0 (1)\\IEDriverServer.exe"); //問題2解決方法


        DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
        ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

WebDriver ie_driver = new InternetExplorerDriver(ieCapabilities); //問題3解決方法


       ie_driver.get("http://www.baidu.com");
       String usr_url = ie_driver.getCurrentUrl();
       System.out.println("User URL:" + usr_url);

}

log結果如下(

1. 對測試程式執行時的功能沒有影響,作為一個warning):

Started InternetExplorerDriver server (32-bit)
       2.33.0.0
       Listening on port 41503
       2013-7-18 14:54:50 org.apache.http.impl.client.DefaultRequestDirector tryExecute
       資訊: I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond
               2013-7-18 14:54:50 org.apache.http.impl.client.DefaultRequestDirector tryExecute
       資訊: Retrying request

       User URL : http://localhost:41503/

2. 提示下面的錯誤:

Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, seehttp://code.google.com/p/selenium/wiki/InternetExplorerDriver. The latest version can be downloaded fromhttp://code.google.com/p/selenium/downloads/list

    解決方法:需要設定IE的Driver到“webdriver.ie.driver”變數中

                      需要新增IEDriverServer.exe(從Selenium官網可下載的),並用如下的程式碼進行設定。
System.setProperty("webdriver.ie.driver","C:\\Users\\li.chunmei\\Downloads\\IEDriverServer_Win32_2.33.0 (1)\\IEDriverServer.exe");

3. 如果IE瀏覽器設定安全性較高,在“Internet Options”中都不要選擇“Enable Protected Mode”(保護模式)!否則會提示下面的錯誤:

Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)

    解決方法有兩種,

    一種是修改掉IE的設定,不要在任何情況下使用保護模式。

   二種是前面程式碼中加入 如下片段在執行時設定IE的Capabilities:

     DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
            ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
            WebDriver ie_driver = new InternetExplorerDriver(ieCapabilities);

4.Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Browser zoom level was set to 89%. It should be set to 100% (WARNING: The server did not provide any stacktrace information)
錯誤原因:IE瀏覽器的比例調大了,按ctrl+0,可以恢復原來的大小,即可。PS:這種錯誤真是。。。讓人無語

5.System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=8, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:36988/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=true, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 6d1ba00b-a372-4598-95b4-a9e00c20ce2c
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

如果遇到上面的問題

解決方法有兩種:
1.是修改掉IE的設定,不要在任何情況下使用保護模式(protected mode)
2.另一種即是前面程式碼中如下片段在執行時設定IE的Capabilities。
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability
      
(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
WebDriver oWebDriver = new InternetExplorerDriver(ieCapabilities);