1.簡介

經過前邊幾篇文章和巨集哥一起的學習,想必你已經知道了如何去檢視Selenium相關介面或者方法。一般來說我們絕大多數看到的是已經封裝好的介面,在檢視介面原始碼的時候,你可以看到這個介面上邊的註釋,它會告訴你這個介面或者方法的作用,有哪些引數以及引數的型別是什麼。為了更加生動的描述和理解,巨集哥舉例通過查詢原始碼的方式去理解selenium啟動Chrome的過程。這一篇文章主要是給沒有java基礎的童鞋或者小夥伴們準備的,為了接下來的學習還是要看一下java基礎知識。

2.selenium啟動Chrome的過程

巨集哥先將啟動Chrome的程式碼附上,對照程式碼跟隨巨集哥的腳步來慢慢的理解。

package lessons;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; /**
* @author 北京-巨集哥
*
* 2021年6月17日
*/
public class LaunchChrome { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe"); //初始化一個chrome瀏覽器例項,例項名稱叫driver
WebDriver driver = new ChromeDriver();
//最大化視窗
driver.manage().window().maximize();
//設定隱性等待時間
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); // get()開啟一個站點
driver.get("https://www.baidu.com");
//getTitle()獲取當前頁面title的值
System.out.println("當前開啟頁面的標題是: "+ driver.getTitle()); //關閉並退出瀏覽器
driver.quit(); } }

2.1包(package)

為了便於管理大型軟體系統中數目眾多的類,解決類命名衝突的問題,Java引入了包(package)。
1. package mybole; //須為首句
   Class Test : main(): println(…..);  類全名就變為:mybole.Test
2. java中的 包 對應windows中的目錄 : java mybole.Test  or  java mybole/Test
---注意:包名可有多層限定名,如:package cn.mybole;
  1) package語句必須是檔案中的第一條語句。也就是說,在package語句之前,除了空白和註釋之外不能有任何語句。
  2) 如果不加package語句,則指定為預設包或無名包。
  3) 包對應著檔案系統的目錄層次結構。
  4) 在package語句中,用“.”來指明包(目錄)的層次。
  一旦有上千個類和多層包,則手動就麻煩,此時怎麼辦呢?
  方法有:javac –d . Test.java    //在當前目錄下系動自動生成 包 對應的 目錄層次結構

3.實際專案中包和類的應用檢視:

---如果去掉上面HelloworldAction.java類中的package,就會報錯。

2.2import

import就是在java檔案開頭的地方,先說明會用到那些類別。
接著我們就能在程式碼中只用類名指定某個類,也就是隻稱呼名字,不稱呼他的姓。 巨集哥匯入的那些都是下邊會用到的。

2.3setProperty

System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");  

按下Ctrl+滑鼠懸停在setProperty上方,點選滑鼠左鍵,可以看到java中setProperty的原始碼。自己去閱讀下程式碼中關於setProperty的介紹。其實就是設定指定鍵對值的系統屬性。上面webdriver.gecko.driver就是鍵,.\\Tools\\geckodriver.exe就是值。這樣就把geckodriver設定成為系統的全域性變數!這個時候driver就相當於一個靜態變數,存放在記憶體裡,直到driver關閉。
所謂的 system porperty,system 指的是 JRE (runtime)system,不是指 OS。
設定指定鍵指示的系統屬性,可以利用系統屬性來載入多個驅動。所以,上面這行程式碼,就是通過鍵和值指定Chrome 的驅動位置。

setProperty原始碼如下:

/**
* Sets the system property indicated by the specified key.
* <p>
* First, if a security manager exists, its
* <code>SecurityManager.checkPermission</code> method
* is called with a <code>PropertyPermission(key, "write")</code>
* permission. This may result in a SecurityException being thrown.
* If no exception is thrown, the specified property is set to the given
* value.
* <p>
*
* @param key the name of the system property.
* @param value the value of the system property.
* @return the previous value of the system property,
* or <code>null</code> if it did not have one.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* setting of the specified property.
* @exception NullPointerException if <code>key</code> or
* <code>value</code> is <code>null</code>.
* @exception IllegalArgumentException if <code>key</code> is empty.
* @see #getProperty
* @see java.lang.System#getProperty(java.lang.String)
* @see java.lang.System#getProperty(java.lang.String, java.lang.String)
* @see java.util.PropertyPermission
* @see SecurityManager#checkPermission
* @since 1.2
*/
public static String setProperty(String key, String value) {
checkKey(key);
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPermission(new PropertyPermission(key,
SecurityConstants.PROPERTY_WRITE_ACTION));
} return (String) props.setProperty(key, value);
}

2.4WebDriver

 WebDriver driver = new ChromeDriver();  

點選檢視WebDriver發現是一個介面,它的備註這樣寫的:WebDriver是一個測試的主要介面,它展現了一個理想化的web瀏覽器,它主要包括三個目錄。1)控制瀏覽器本身 2)查詢和選擇元素 3)除錯程式,比如異常處理。
       driver這裡是一個例項物件,學習了Java中類和物件,就應該不難理解。
       new 是一個關鍵字,Java中通過new這個關鍵字,可以在記憶體中開闢一塊空間,用來載入變數。
ChromeDriver(),是WebDriver這個介面在chrome上的一個實現具體類。ChromeDriver這個類裡面,還包含一些chrome瀏覽器的一些選項設定。這行程式碼的意思用一句話來講:初始化一個chrome型別的driver例項物件。這裡除了chrome,還有IE,Safari,firefox等對應的driver啟動方法,你可以檢視*\Selenium-Java-src\org\openqa\selenium,可以找到這些介面檔案。

WebDriver原始碼如下(很多巨集哥剪貼了一部分):

/**
* WebDriver is a remote control interface that enables introspection and control of user agents
* (browsers). The methods in this interface fall into three categories:
* <ul>
* <li>Control of the browser itself</li>
* <li>Selection of {@link WebElement}s</li>
* <li>Debugging aids</li>
* </ul>
* <p>
* Key methods are {@link WebDriver#get(String)}, which is used to load a new web page, and the
* various methods similar to {@link WebDriver#findElement(By)}, which is used to find
* {@link WebElement}s.
* <p>
* Currently, you will need to instantiate implementations of this interface directly. It is hoped
* that you write your tests against this interface so that you may "swap in" a more fully featured
* browser when there is a requirement for one.
* <p>
* Most implementations of this interface follow
* <a href="https://w3c.github.io/webdriver/">W3C WebDriver specification</a>
*/
public interface WebDriver extends SearchContext {

2.5driver

driver.manage().window().maximize();

這裡driver,就是指上面我們初始化的chrome的例項物件,就是類似一個真實瀏覽器。manage是Options這個介面的一個方法,window().maximize(),window也是一個介面,這個介面下,有maximize這個方法,也就是最大化瀏覽器,window下也有全屏,設定視窗大小的方法。

2.6manage

driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);

manage上面提到是一個方法,直接來看timeouts,timeouts是介面Timeouts的一個例項物件,它的左右是針對webdriver例項管理超時的一個介面。implicitlyWait是一個隱式等待,當在一定時間內,如果還沒有找到頁面元素,就報超時。引數有兩個,第一個是8,第二個是時間單位,這裡選擇秒,所以這裡是8秒後超時。

manage原始碼如下:

/**
* Gets the Option interface
*
* @return An option interface
* @see org.openqa.selenium.WebDriver.Options
*/
Options manage();

2.7get

driver.get("https://www.baidu.com");

這裡的get方法的作用是,在當前瀏覽器視窗,載入一個新的web頁面,是通過http get發生請求完成的。引數型別是String,一般是url。get方法就是開啟一個網頁的作用。

get原始碼,如下:

/**
* Load a new web page in the current browser window. This is done using an HTTP POST operation,
* and the method will block until the load is complete (with the default 'page load strategy'.
* This will follow redirects issued either by the server or as a meta-redirect from within the
* returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until
* this timeout is over, since should the underlying page change whilst your test is executing the
* results of future calls against this interface will be against the freshly loaded page. Synonym
* for {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
* <p>
* See <a href="https://w3c.github.io/webdriver/#navigate-to">W3C WebDriver specification</a>
* for more details.
*
* @param url The URL to load. Must be a fully qualified URL
* @see org.openqa.selenium.PageLoadStrategy
*/
void get(String url);

2.8quit

driver.quit();

退出有quit和close兩種,這裡quit表示退出當前瀏覽器,關閉這個瀏覽器有關聯的所有視窗。

quit原始碼,如下:

/**
* Quits this driver, closing every associated window.
*/
void quit();

3.小結

好了,今天巨集哥就吊打到這裡,文章中的原始碼註釋英文巨集哥就沒有翻譯,其實很簡單的,實在不懂的自己可以用翻譯軟體看一下是什麼意思。下面文章開始介紹Selenium中的常見方法或者介面的具體使用例子。