如何使用Selenium Webdriver連線到已開啟的瀏覽器?


我們可以使用Selenium webdriver連線到已開啟的瀏覽器。這可以透過使用**Capabilities**和**ChromeOptions**類來實現。Capabilities類使用**getCapabilities**方法獲取瀏覽器功能。

這通常用於除錯目的,當測試中有大量步驟並且我們不想重複相同的步驟時。首先,我們將啟動瀏覽器並在下面的編輯框中輸入一些文字。

示例

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.By;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ConnectBrwSession{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //get browser capabilities in key value pairs
      Capabilities c = driver.getCapabilities();
      Map<String, Object> m = c.asMap();
      m.forEach((key, value) −> {
         System.out.println("Key is: " + key + " Value is: " + value);
      });
      //set implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      //identify element
      WebElement l = driver.findElement(By.id("gsc−i−id1"));
      l.sendKeys("Selenium");
   }
}

輸出

我們將記下從**控制檯輸出**獲得的引數**{debuggerAddress=localhost:61861}**,將其新增到ChromeOptions物件中。

瀏覽器視窗 -

現在,讓我們連線到同一個瀏覽器會話並對其執行一些操作。連線到現有會話時,不應使用瀏覽器**關閉或退出**方法。

示例

連線到同一會話所做的程式碼修改。

import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.By;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class ConnectBrwSession{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //object of ChromeOptions class
      ChromeOptions o = new ChromeOptions();
      //setting debuggerAddress value
      o.setExperimentalOption("debuggerAddress", "localhost:61861");
      //add options to browser capabilities
      Capabilities c = driver.getCapabilities(o);
      Map<String, Object> m = c.asMap();
      m.forEach((key, value) −> {
         System.out.println("Key is: " + key + " Value is: " + value);
      });
      //set implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //identify element
      WebElement l = driver.findElement(By.id("gsc−i−id1"));
      //remove existing data in edit box
      l.clear();
      l.sendKeys("Tutorialspoint");
      String s = l.getAttribute("value");
      System.out.println("Attribute value: " + s);
   }
}

輸出

瀏覽器視窗

更新於:2021年1月30日

6000+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.