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中的常見方法或者接口的具體使用例子。