Skip to content

复用浏览器


常见的浏览器复用场景

  • 多个测试用例复用同一个浏览器实例
  • 多个标签页或窗口

复用浏览器应用场景

  1. 便于绕开防自动化机制
  2. 便于调试代码
  3. 提高运行效率

浏览器复用的优点

  • 节省时间
  • 资源优化
  • 更高效的内存管理


复用已有浏览器-配置步骤

  1. 需要退出当前所有的chrome浏览器(特别注意)。

  2. 输入启动命令,通过命令启动chrome浏览器

    • 找到 chrome 的启动路径
    • 配置环境变量
    • windows:chrome --remote-debugging-port=9222
    • mac:Google\ Chrome --remote-debugging-port=9222
  3. 验证是否启动成功

    • 访问浏览器查看浏览器是否启动 http://localhost:9222/

windows 环境变量配置

  1. 找到 chrome 可执行文件路径,如图一
  2. 配置环境变量,如图二
  3. 启动 chrome 浏览器,如图三
  4. 访问 http://localhost:9222/

图一

图二 图三


Mac 环境变量配置

  1. 获取启动路径(注意:使用 tab 键,不要手动输入)。
  2. 将启动路径配置到环境变量中。
# 举例,不要生搬硬套
export PATH=$PATH:/Applications/Google\ Chrome.app/Contents/MacOS

复用已有浏览器-代码设置

# python 代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

option = Options()
option.debugger_address = "localhost:9222"
driver = webdriver.Chrome(options=option)
driver.implicitly_wait(10)
driver.get("https://work.weixin.qq.com/wework_admin/frame")
# 人工扫码
time.sleep(10)
# 点击通讯录
driver.find_element(By.XPATH,'//*[text()="通讯录"]').click()
/ java 代码
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
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.chrome.ChromeOptions;
public class web_useAgainTest {
    static WebDriver driver;
    @BeforeAll
    static void setup(){
        ChromeOptions chromeOptions =new ChromeOptions();
        chromeOptions.setExperimentalOption("debuggerAddress","localhost:9222");
        driver=new ChromeDriver(chromeOptions);



    }
    @AfterAll
    static void teardown(){
      driver.quit();

    }


    @Test
    void remote2() throws InterruptedException {

        driver.get("https://work.weixin.qq.com/wework_admin/frame");
        //人工扫码
        Thread.sleep(30000);

        WebElement element = driver.findElement(By.xpath("//*[@class ='index_service_cnt_itemWrap']"));
        element.click();
        Thread.sleep(1000);
    }

}

总结

复用浏览器是指在启动 selenium 程序时,浏览器不另外打开一个新的页面,而是直接使用现有的浏览器页面,并进行操作。