Selenium 是否可以与现有的浏览器会话交互?


我们可以与现有的浏览器会话交互。通过使用 CapabilitiesChromeOptions 类来执行此操作。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.com/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);
   }
}

输出

浏览器窗口 −

更新于: 2021-02-01

4K+ 阅读次数

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.