使用Selenium控制已经打开的浏览器

1. 场景

有时候网站需要扫码登录或者验证码登录,使用selenium启动的浏览器进程登录较为麻烦。需要手动辅助登录,再进行selenium自动化。

2. 步骤

  1. 启动一个Chrome的debug进程,设置端口为9222
  2. 通过webdriver连接到Chrome的9222端口
  3. Selenium通过webdriver控制chrome

3. 例子-Chrome

找到本机chrome.exe的位置

# windows
    C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
# mac
  /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

通过命令行启动ChromeDebug模式

//windows cd到chrome所在的文件夹下,再以debug模式启动
$ chrome.exe  --remote-debugging-port=9222
//前面是本地安装好的chrome浏览器的启动路径
//mac
$ /Applications/Google\Chrome.app/Contents/MacOS/Google\ Chrome -remote-debugging-port=9222
//启动浏览器debug模式前需要把浏览器所有打开的进程关掉
//9222是默认端口,可以修改,但不要使用以及被占用的端口
//注意mac上如果提示没有该文件,可以通过设置.bash_profile里的path,加上chrome的路径,就可以使用Google\ Chrome作为命令了

4. 在代码中连接调试打开的debug的chrome窗口

Python版(未试验)

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

options = webdriver.ChromeOptions()
options.debugger_address ="127.0.0.1:9222"
self.driver
webdriver.Chrome(options=options)

Java版 (已试验)

System.setProperty("webdriver.chrome.driver", "D:\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222"); //此处的端口号一定要ChromeDebug模式启动的端口号相同
//否则报错: Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot connect to chrome at 127.0.0.1:9222
//from chrome not reachable

WebDriver driver = new ChromeDriver(options);
System.out.println(driver.getTitle());

Reference:
[1] Selenium 控制已经打开的浏览器 (Chrome & Java版) 及 Chrome配置
[2] 使用selenium接管已打开的浏览器

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容