如何在自动化中保持长 Selenium 脚本的会话有效?
seleniumautomation testingtesting tools更新于 2026/2/16 19:07:17
我们可以在自动化中保持长 Selenium 脚本的会话有效。在 Chrome 浏览器中,这可以借助 ChromeOptions 和 Capabilities 类来实现。
Capabilities 类可以使用 getCapabilities 方法获取浏览器的功能。此技术通常用于在包含大量步骤的场景中调试特定步骤。
首先,让我们尝试在以下页面中突出显示的编辑框中输入文本 −

Code Implementation
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 BrwSessionAlive{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//obtain browser capabilities
Capabilities cap = driver.getCapabilities();
Map<String, Object> mp = cap.asMap();
mp.forEach((key, value) -> {
System.out.println("Key is: " + key + " Value is: " + value);
});
//implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//url launch
driver.
get("https://www.tutorialspoint.com/about/about_careers.htm");
//identify element
WebElement e = driver.findElement(By.id("gsc-i-id1"));
e.sendKeys("Selenium");
}
}
输出

在上图中,我们突出显示了值为 localhost:61861 的参数 debuggerAddress。我们将把这个键值对添加到 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 BrwSessionAlive{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//instance of ChromeOptions
ChromeOptions op = new ChromeOptions();
//configure debuggerAddress value
op.setExperimentalOption("debuggerAddress", "localhost:61861");
//obtain browser capabilities
Capabilities cap = driver.getCapabilities(op);
Map<String, Object> mp = cap.asMap();
mp.forEach((key, value) -> {
System.out.println("Key is: " + key + " Value is: " + value);
});
//implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//identify element
WebElement e = driver.findElement(By.id("gsc-i-id1"));
//clear existing data
e.clear();
e.sendKeys("Tutorialspoint");
String str = e.getAttribute("value");
System.out.println("Attribute value: " + str);
}
}
输出

浏览器


