使用 selenium 连接已经打开的 chrome 浏览器

最近做在一些 web 自动化(其实是用 web 端来配置网络设备)
编写脚本时经常用到 debug 去提取网页中的一些元素并做测试,但是每次需要 debug 时都要打开新的浏览器,比较麻烦,所以如果能直接连接到已经打开的浏览器,会非常方便。

操作步骤:

  1. 使用参数启动浏览器
    cmd 定位到 chrome 所在目录,使用以下参数启动:

    1
    C:\Program Files (x86)\Google\Chrome\Application> .\chrome.exe --remote-debugging-port=9999 --user-data-dir="C:\test"

    截图
    参数:
    port 可以是任意端口,只要不和本地已开放的端口冲突即可;用户目录最好是一个空文件夹,浏览器启动时会以空配置启动,然后将初始化配置放到这个目录里面。

    另一种简单的方法:可以在桌面新建一个 chrome 的快捷方式,然后再目标里面写上参数(方便,推荐)。
    截图

  1. 在 python 中连接已打开的浏览器

    代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options

    chrome_options = Options()
    chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9999")
    # selenium 运行时会从系统的环境变量中查找 webdriver.exe
    # 一般把 webdriver.exe 放到 python 目录中,这样就不用在代码中指定。
    chrome_driver = "C:\chromedriver.exe"
    driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
    driver.get(https://www.baidu.com/")
    print(driver.title)
    driver.quit()

这样就可以直接操作 步骤1 中打开的浏览器了,其他浏览器同理。