Selenium 是否可以與現有的瀏覽器會話互動?
我們可以與現有的瀏覽器會話互動。透過使用 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 ConnectExistingSession{
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.WebDriver;
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 java.util.concurrent.TimeUnit;
public class ConnectExistingSession{
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);
}
}輸出

瀏覽器視窗 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP