• Selenium Video Tutorials

Selenium WebDriver 安裝



Selenium是一個自動化測試工具,幫助我們自動化Web應用程式的測試。在安裝Selenium WebDriver之前,我們首先需要確定使用哪種語言來開發Selenium測試,因為有多種語言支援Selenium。

使用Java安裝Selenium WebDriver

步驟1 - 我們需要下載並安裝Java到本地系統。可以透過訪問以下連結完成:Java 下載

成功安裝Java後,我們可以在命令提示符中執行命令:java 來確認安裝。

C:\java 

螢幕上將顯示以下資訊:

Usage: java [options] <mainclass> [args...]
           (to execute a class)
   or  java [options] -jar <jarfile> [args...]
           (to execute a jar file)
   or  java [options] -m <module>[/<mainclass>] [args...]
       java [options] --module <module>[/<mainclass>] [args...]
           (to execute the main class in a module)
   or  java [options] <sourcefile> [args]
           (to execute a single source-file program)

 Arguments following the main class, source file, -jar <jarfile>,
 -m or --module <module>/<mainclass> are passed as the arguments to
 main class.

 where options include:

    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
    --class-path <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -p <module path>
    --module-path <module path>...
                  A ; separated list of directories, each directory
                  is a directory of modules.
    --upgrade-module-path <module path>...
                  A ; separated list of directories, each directory
                  is a directory of modules that replace upgradeable
                  modules in the runtime image
    --add-modules <module name>[,<module name>...]
                  root modules to resolve in addition to the initial module.
                  <module name> can also be ALL-DEFAULT, ALL-SYSTEM,
                  ALL-MODULE-PATH.
    --enable-native-access <module name>[,<module name>...]
                  modules that are permitted to perform restricted native operations.
                  <module name> can also be ALL-UNNAMED.
    --list-modules
                  list observable modules and exit
    -d <module name>
    --describe-module <module name>
                  describe a module and exit
    --dry-run     create VM and load main class but do not execute main method.
                  The --dry-run option may be useful for validating the
                  command-line options such as the module system configuration.
    --validate-modules
                  validate all modules and exit
                  The --validate-modules option may be useful for finding
                  conflicts and other errors with modules on the module path.
    -D<name>=<value>
                  set a system property
    -verbose:[class|module|gc|jni]
                  enable verbose output for the given subsystem
    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit
    -showversion  print product version to the error stream and continue
    --show-version
                  print product version to the output stream and continue
    --show-module-resolution
                  show module resolution output during startup
    -? -h -help
                  print this help message to the error stream
    --help        print this help message to the output stream
    -X            print help on extra options to the error stream
    --help-extra  print help on extra options to the output stream
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:jdwp
                  see also -agentlib:jdwp=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
                  HiDPI scaled images are automatically supported and used
                  if available. The unscaled image filename, e.g. image.ext,
                  should always be passed as the argument to the -splash option.
                  The most appropriate scaled image provided will be picked up
                  automatically.
                  See the SplashScreen API documentation for more information
    @argument files
                  one or more argument files containing options
    --disable-@files
                  prevent further argument file expansion
    --enable-preview
                  allow classes to depend on preview features of this release
To specify an argument for a long option, you can use --<name>=<value> or
--<name> <value>.

接下來,我們將透過執行以下命令來確認已安裝的Java版本:

java –version

將顯示以下輸出:

openjdk version "17.0.9" 2023-10-17
OpenJDK Runtime Environment Homebrew (build 17.0.9+0)
OpenJDK 64-Bit Server VM Homebrew (build 17.0.9+0, mixed mode, sharing)

執行的命令輸出將表示系統中安裝的Java版本。

要更詳細地瞭解如何設定Java,請參考以下連結:Java環境設定

步驟2 - 使用以下連結在系統中安裝Maven:下載Apache Maven

接下來,我們將透過執行以下命令來確認已安裝的Maven版本:

mvn –version

將顯示以下輸出:

Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)
Maven home: /opt/homebrew/Cellar/maven/3.9.6/libexec
Java version: 21.0.1, vendor: Homebrew, runtime: /opt/homebrew/Cellar/openjdk/21.0.1/libexec/openjdk.jdk/Contents/Home
Default locale: en_IN, platform encoding: UTF-8
OS name: "mac os x", version: "14.0", arch: "aarch64", family: "mac"

執行的命令輸出將表示系統中安裝的Maven版本。

步驟3 - 安裝IntelliJ編輯器來執行Selenium測試。市場上有許多可用的編輯器,例如:Eclipse,IntelliJ,Atom等等。使用這些編輯器,我們可以開始一個專案,開始在Selenium上進行測試自動化。

步驟4 - IntelliJ編輯器設定應已成功完成。

步驟5 - 在Main.java檔案中新增以下程式碼。

示例1

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import java.util.concurrent.TimeUnit;

public class Main {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new EdgeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
      
      // URL launch 
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");

      // get browser title after browser launch
      System.out.println("Browser title: " + driver.getTitle());

   }
}

在pom.xml檔案中新增的依賴項:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.19.0</version>
      </dependency>
   </dependencies>
</project>

步驟6 - 執行測試並等待執行完成

步驟7 - Edge瀏覽器啟動,我們在控制檯中得到了輸出訊息 - 瀏覽器標題:Selenium實踐 - 學生登錄檔單程序已完成,退出程式碼為0,表示程式碼成功執行。

輸出

Browser title: Google

Process finished with exit code 0

同時,Edge瀏覽器啟動時頂部顯示訊息Edge正在被自動化測試軟體控制

示例2

讓我們來看另一個例子,我們將啟動瀏覽器,開啟一個URL,獲取瀏覽器標題,最後退出瀏覽器。

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import java.util.concurrent.TimeUnit;

public class MainBrowserQuit {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new EdgeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // URL launch and get the browser title
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");
      System.out.println( "Browser title after launch: " + driver.getTitle());
      
      // close browser
      driver.quit();
   }
}

輸出

Browser title after launch: Selenium Practice - Student Registration Form

Process finished with exit code 0

在上面的例子中,我們首先啟動了Edge瀏覽器,然後檢索了瀏覽器標題,然後退出了瀏覽器,在控制檯中收到了訊息 - 啟動後瀏覽器標題:Selenium實踐 - 學生登錄檔單

最後,收到了訊息程序已完成,退出程式碼為0,表示程式碼成功執行。

結論

本教程對Selenium安裝進行了全面講解。我們從介紹使用Java安裝Selenium WebDriver開始,並透過示例說明如何在Selenium WebDriver中啟動瀏覽器然後退出瀏覽器。這使您能夠深入瞭解Selenium的安裝。建議您多加練習所學內容,並探索其他與Selenium相關的知識,以加深理解並拓寬視野。

廣告
© . All rights reserved.