• Selenium Video Tutorials

Selenium WebDriver - JSON 資料檔案



Selenium WebDriver 可用於與 JSON 資料檔案互動。在自動化測試中,經常需要透過 JSON 檔案為測試用例提供大量資料,以驗證特定場景或建立資料驅動框架。JSON 檔案以鍵值對形式包含資料,其副檔名為 .json。

Java 提供了一些類和方法,可以使用 JSON Simple 庫對 JSON 檔案執行讀寫資料操作。JSON Simple 是一個輕量級的庫,用於操作 JSON 物件。

如何安裝 JSON Simple?

步驟 1 - 從以下連結新增 JSON Simple 依賴項:

https://mvnrepository.com/artifact/.

步驟 2 - 儲存包含所有依賴項的 pom.xml 檔案並更新 Maven 專案。

示例 1 - 從 JSON 檔案讀取所有值

讓我們以名為 Detail.json 的 JSON 檔案為例,我們將讀取整個 JSON 檔案並使用 JSONParser 類及其 parse() 方法檢索其所有值。

Seleniu JSON File 1

Detail.json 檔案的內容如下:

{
   "name": "Ram",
   "email": "abc@gmail.com",
   "home": [
      {
         "road": "TUY",
         "zip": "700008"
      },
      {
         "road": "TUX",
         "zip": "700061"
      }
   ]
}

從 Detail.json 檔案檢索值後,我們將把 name 和 email 鍵的值輸入到以下頁面中的 全名電子郵件 欄位中。

Seleniu JSON File 2

請注意:Details.json 檔案放置在專案下的 Resources 資料夾中,如下圖所示。

Seleniu JSON File 3

JSONRead.java 類檔案的程式碼實現。

package org.example;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class JSONRead {
   public static void main(String[] args) throws IOException, ParseException {

      //object of JSONParser
      JSONParser j = new JSONParser();

      // load json file to be read
      FileReader f = new FileReader("./Resources/Detail.json");

      // parse json content
      Object o = j.parse(f);

      // convert parsing object to JSON object
      JSONObject detail = (JSONObject)o;

      // get values from JSON file
      String name = (String)detail.get("name");
      String email = (String)detail.get("email");
      System.out.println("First Name: " + name);
      System.out.println("Email: " + email);

      // get values from JSON array
      JSONArray h = (JSONArray)detail.get("home");

      // iterate through the JSONArray
      for(int i = 0; i < h.size(); i ++){
         JSONObject home = (JSONObject) h.get(i);
         String road = (String)home.get("road");
         String zip = (String)home.get("zip");
         System.out.println("Road: " + road);
         System.out.println("Zip: " + zip);
      }
      
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

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

      // Opening the webpage
      driver.get("https://tutorialspoint.tw/selenium/practice/text-box.php");

      //Identify elements
      WebElement n = driver.findElement(By.xpath("//*[@id='fullname']"));
      WebElement m = driver.findElement(By.xpath("//*[@id='email']"));

      // enter name and email after reading from JSON file
      n.sendKeys(name);
      m.sendKeys(email);

      // get values entered
      String enteredName = n.getAttribute("value");
      String enteredEmail = m.getAttribute("value");
      System.out.println("Entered Name: " + enteredName);
      System.out.println("Entered Email: " + enteredEmail);

      // quitting browser
      driver.quit();
   }
}

新增到 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.11.0</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
         <groupId>com.googlecode.json-simple</groupId>
         <artifactId>json-simple</artifactId>
         <version>1.1.1</version>
      </dependency>
   </dependencies>
</project>

輸出

First Name: Ram
Email: abc@gmail.com
Road: TUY
Zip: 700008
Road: TUX
Zip: 700061
Entered Name: Ram
Entered Email: abc@gmail.com

Process finished with exit code 0

在上面的示例中,我們讀取了整個 JSON 檔案,並在控制檯中獲得了其所有值,訊息為 - 姓名:Ram,電子郵件:abc@gmail.com,道路:TUY,郵編:700008,道路:TUX郵編:700061。然後,將透過讀取 JSON 檔案獲得的姓名和電子郵件的值輸入到網頁上的輸入框中,並在控制檯中也檢索到輸入的值,訊息為 - 輸入的姓名:Ram輸入的電子郵件:abc@gmail.com

最後,收到訊息 Process finished with exit code 0,表示程式碼已成功執行。

示例 2 - 在 JSON 檔案中寫入和讀取值

讓我們再舉一個例子,我們將建立一個名為 Detail1.json 的 JSON 檔案,該檔案位於專案中的 Resources 資料夾下,並在其中寫入一些值。

package org.example;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class JSONReadWrite {
   public static void main(String[] args) throws IOException, ParseException {

      // object of JSONObject
      JSONObject j = new JSONObject();

      // generate key-value pairs in JSON file
      j.put("Name", "Selenium");
      j.put("Language", "Java");

      // create JSON file with no duplicate values
      FileWriter f = new FileWriter("./Resources/Detail1.json", false);

      // write on json file
      f.write(j.toJSONString());

      // close file after write
      f.close();

      //object of JSONParser
      JSONParser j1 = new JSONParser();

      // load json file to be read
      FileReader f1 = new FileReader("./Resources/Detail1.json");

      // parse json content
      Object o = j1.parse(f1);

      // convert parsing object to JSON object
      JSONObject detail = (JSONObject)o;

      // get values from JSON file
      String name = (String)detail.get("Name");
      String language = (String)detail.get("Language");
      System.out.println("Name: " + name);
      System.out.println("Language: " + language);
   }
}

新增到 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.11.0</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
         <groupId>com.googlecode.json-simple</groupId>
         <artifactId>json-simple</artifactId>
         <version>1.1.1</version>
      </dependency>
   </dependencies>
</project>

輸出

Name: Selenium
Language: Java

Process finished with exit code 0

在上面的示例中,我們在專案中的 Resources 資料夾下建立了一個名為 Detail1.json 的 JSON 檔案,並在其中寫入了一些值。然後我們讀取所有這些值,最後在控制檯中以訊息的形式獲得它們 - 名稱:Selenium語言:Java

最後,收到訊息 Process finished with exit code 0,表示程式碼已成功執行。

此外,名為 Detail1.csv 的 JSON 檔案已在專案目錄中建立。單擊它,我們將獲得透過上述程式碼寫入的值。

Seleniu JSON File 4

這總結了我們關於 Selenium WebDriver - JSON 資料檔案的教程的全面內容。我們首先描述了什麼是 JSON Simple 庫,如何安裝 JSON Simple,並逐步講解了如何在使用 JSON Simple 和 Selenium WebDriver 的情況下讀取和寫入 JSON 檔案中的值的示例。這使您能夠深入瞭解 Selenium WebDriver 中的 JSON 資料檔案。最好不斷練習您所學的內容,並探索與 Selenium 相關的其他內容,以加深您的理解並拓寬您的視野。

廣告
© . All rights reserved.