• Selenium Video Tutorials

Selenium WebDriver - 處理 Ajax 呼叫



Selenium Webdriver 可用於處理 Ajax 呼叫。Ajax 也稱為非同步 JavaScript,主要由XMLJavaScript 組成。從 UI 的角度來看,會向伺服器發出 JavaScript 呼叫,然後我們從伺服器以 XML 格式接收響應。

什麼是 Ajax?

Ajax 或非同步 JavaScript 主要用於建立快速且響應靈敏的網頁。讓我們以一個網頁為例,在這個網頁中,使用者資訊會在點選按鈕時更新。假設使用者頻繁更新其資訊,因此每次都需要重新載入整個網頁。但是,在基於 Ajax 構建的網頁上,只需要更新使用者修改的那部分使用者資訊,而無需重新載入整個頁面。

Ajax 相容 HTTP 請求、JavaScript、XML、HTMLCSS 等技術。Ajax 以非同步方式傳送和接收資料,無需重新載入頁面。

在 Ajax 系統中,使用者介面向 XML HTTP 請求回撥方法傳送 JavaScript 呼叫,然後將 HTTP 請求傳送到 Web 伺服器。接下來,Web 伺服器根據請求與資料庫交換資訊,並以 JSON/XML 格式獲取資訊以反映在使用者介面中。

Selenium 如何處理 Ajax 呼叫?

Selenium Webdriver 並不總是能夠在 Ajax 呼叫後成功訪問 Web 元素。這是因為在 Ajax Web 應用程式中,元素可用的等待時間並不統一。Selenium 測試會等待特定時間,之後我們可能會遇到失敗。無法預測 Ajax 呼叫的時間是 Selenium 測試面臨的挑戰。

為了克服這個問題,Selenium 使用以下同步和等待機制:

Thread.sleep()

此命令會暫停執行,暫停時間由傳遞的引數決定。但是,這不是一個好的選擇,因為等待時間是固定的,但是無法預測 Ajax 呼叫的時間。此外,此命令會將當前執行緒從執行佇列移動到等待佇列。

隱式等待

這是 Selenium 中提供的預設等待。它是一種適用於整個驅動程式會話的全域性等待。預設等待時間為 0,這意味著如果未找到元素,則會立即丟擲錯誤。但是,如果設定了等待時間,則在等待時間超過後會丟擲錯誤。一旦識別出元素,就會返回其引用,然後執行轉到下一步。我們應該以最佳方式使用隱式等待,較長的等待時間會增加測試的執行時間。

顯式等待

這種型別的等待非常適合處理 Ajax 呼叫。一些顯式等待的預期條件如下:

  • titleContains
  • alertIsPresent
  • invisibilityOfElementLocated
  • titleIs
  • invisibilityOfElementWithText
  • visibilityOf
  • textToBePresentInElement
  • visibilityOfElementLocated
  • visibilityOfAllElements
  • presenceOfAllElementsLocatedBy
  • presenceOfElementLocated
  • elementToBeClickable
  • stalenessOf
  • textToBePresentInElementValue
  • textToBePresentInElementLocated
  • elementSelectionStateToBe
  • elementToBeSelected
  • frameToBeAvaliableAndSwitchToIt

流暢等待

這是驅動程式等待特定元素條件為真的最長時間。它還確定驅動程式在定位元素或丟擲異常之前驗證的間隔(輪詢間隔)。

使用顯式等待處理 Ajax

讓我們以以下頁面為例,我們將在其中點選點選我

Selenium Handling Ajax Calls 1

點選點選我後,我們將藉助顯式等待並等待網頁上出現文字您已執行動態點選

Selenium Handling Ajax Calls 2

示例

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

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

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

      // launching a browser
      driver.get("https://tutorialspoint.tw/selenium/practice/buttons.php");

      // identify button then click on it
      WebElement l = driver.findElement
         (By.xpath("/html/body/main/div/div/div[2]/button[1]"));
      l.click();

      // Identify text
      WebElement e = driver.findElement(By.xpath("//*[@id='welcomeDiv']"));

      // explicit wait to expected condition for presence of a text
      WebDriverWait wt = new WebDriverWait(driver, Duration.ofSeconds(2));
      wt.until(ExpectedConditions.presenceOfElementLocated
         (By.xpath("//*[@id='welcomeDiv']")));

      // get text
      System.out.println("Get text after clicking: " + e.getText());

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

輸出

Get text after clicking: You have done a dynamic click

Process finished with exit code 0

在上述示例中,點選點選我按鈕後出現的文字為您已執行動態點選

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

使用流暢等待處理 Ajax

讓我們再以以下頁面為例,我們將在其中點選顏色更改

Selenium Handling Ajax Calls 3

點選顏色更改後,我們將藉助流暢等待並等待網頁上出現文字為5 秒後可見的按鈕。

Selenium Handling Ajax Calls 4

示例

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import java.time.Duration;

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

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

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/dynamic-prop.php");

      // identify button then click
      WebElement l = driver.findElement(By.xpath("//*[@id='colorChange']"));
      l.click();

      // fluent wait of 6 secs till other button appears
      Wait<WebDriver> w = new FluentWait<WebDriver>(driver)
         .withTimeout(Duration.ofSeconds(20))     .pollingEvery(Duration.ofSeconds(6))
         .ignoring(NoSuchElementException.class);

      WebElement m = w.until
         (ExpectedConditions.visibilityOfElementLocated
         (By.xpath("//*[@id='visibleAfter']")));

      // checking button presence
      System.out.println("Button appeared: " + m.isDisplayed());

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

輸出

Button appeared: true

使用隱式等待處理 Ajax

讓我們以以下頁面為例,我們將在其中嘗試使用錯誤的 xpath 值定位文字Selenium 自動化實踐表單並使用隱式等待。在此期間,一旦超時時間過去,應該會丟擲 NoSuchElementException。

此元素正確的xpath應該是:/html/body/div/header/div[2]/h1。但是,為了產生異常,我們在實現中將使用錯誤的xpath - /html/body/div/header/div[2]/u1

Selenium Handling Ajax Calls 5

示例

package org.example;

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

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

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

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

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");

      // identify element with incorrect xpath value
      WebElement l = driver.findElement(By.xpath("/html/body/div/header/div[2]/u1"));
      l.click();

      // get text
      System.out.println("Get text : " + l.getText());

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

輸出

Exception in thread "main" 
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: 
{"method":"xpath","selector":"/html/body/div/header/div[2]/u1"}
  (Session info: edge=121.0.6167.160)
For documentation on this error, please visit: https://selenium.programming.tw/documentation/webdriver/troubleshooting/errors#no-such-element-exception

Process finished with exit code 1

在上面的例子中,由於使用了錯誤的xpath值來定位文字,我們得到了NoSuchElementException異常。當2秒的隱式等待時間過去後,我們得到了異常。

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

結論

這總結了我們關於Selenium Webdriver處理Ajax呼叫的教程的全面概述。我們從描述什麼是Ajax,Selenium如何處理Ajax開始,並逐步介紹瞭如何使用顯式、隱式和流暢等待來處理Ajax以及Selenium的示例。這使您具備了處理Ajax呼叫的深入知識。明智的做法是不斷練習您學到的知識,並探索與Selenium相關的其他知識,以加深您的理解並擴充套件您的視野。

廣告

© . All rights reserved.