selenium 使用使用已经打开的浏览器

我们在做selenium做UI自动化的时候,chrome 一般都会启动一个新的浏览器。有一个测试,我在chrome安装了油猴插件,新打开的浏览器就没有插件,使用起来就不方便,这样就需要selenium 能直接操作我手动打开的浏览器,在这样的基础上,测试就方便多了。

那么怎样才能让 selenium直接操作我手动打开的浏览器,步骤如下:

1、windows系统命令行中启动chrome浏览器,并且启用一个监听端口9887(也可以设置其他没有使用过的端口,在命令行中自己定义)

start chrome  --flag-switches-begin --flag-switches-end --remote-debugging-port=9887

2、启动命令后,使用命令检测端口是否启用,并且是否是chrome进程

netstat -ano |findstr 9887   #检查端口是否开启
tasklist  |findstr 20428   #查找进程

  执行结果如下:

C:\Program Files\Google\Chrome\Application>start chrome  --flag-switches-begin --flag-switches-end --remote-debugging-port=9887

C:\Program Files\Google\Chrome\Application>netstat -ano |findstr 9887
  TCP    127.0.0.1:9887         0.0.0.0:0              LISTENING       20428
  TCP    127.0.0.1:9887         127.0.0.1:57870        FIN_WAIT_2      340
  TCP    127.0.0.1:9887         127.0.0.1:57871        TIME_WAIT       0
  TCP    127.0.0.1:57870        127.0.0.1:9887         CLOSE_WAIT      9436

C:\Program Files\Google\Chrome\Application>tasklist  |findstr 20428
chrome.exe                   20428 Console                    1    158,120 K

C:\Program Files\Google\Chrome\Application>

 

 3、在selenium脚本中 使用现有浏览器

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9887")
# driver就是当前浏览器窗口
driver = webdriver.Chrome(options=chrome_options)
time.sleep(2)
driver.get("https://www.baidu.com")

 欢迎关注技术微信公众号:

 

 

posted @ 2022-09-10 11:04  testway  阅读(4610)  评论(0编辑  收藏  举报