[selenium] reuse browser (debugger)

selenium debug mode, remote debugging, reuse browser.

Scenes

For example, to test the JD.com shopping process, you must scan the code and log in successfully before proceeding with subsequent operations.

When writing and debugging use cases, a new browser window will be opened every time it is run, and you have to scan the code to log in again.

The reason is that ChromeDriverby default, a new session will be loaded every time it is called and started, which is a waste of time for such frequent debugging scenarios.

For this, the capability ChromeDriveris provided by opening the remote port debug.

Set the parameters in the ChromeOptionsdebuggerAddress object to the address of the debugger server to be connected, in the format:

<hostname/ip:port>

That is, the subsequent operations are performed in the current window to achieve the purpose of browser reuse.

configuration

  1. will chromedriverbe added to the environment variable;
# bin 目录已经配置好环境变量
# 这里可以直接将下载好的 driver 放到该目录下
$ mv chromedriver /usr/local/bin
  1. Settings - Privacy Settings and Security - Website Settings - Background Synchronization - Default Behavior - Check the recently closed website to complete the data sending and receiving operation;

  2. Completely close the browser, click the right mouse button - exit;

  3. Open the browser remote debugging port, this port can be customized, as long as it does not conflict with the local opened port;

$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome -remote-debugging-port=9222
# 正在现有的浏览器会话中打开。
# 如果出现上面提示,重新关闭浏览器,执行命令
  1. Execute the script options, add IPthe address and port number of the remote browser, and execute the test.
@pytest.fixture(scope="session")
def driver():
    options = Options()
    # 设置复用浏览器的端口,地址
    options.debugger_address = "127.0.0.1:9222"
    driver = webdriver.Chrome(options=options)
    driver.get("https://baidu.com")
    yield driver
    driver.quit()


def test_demo(driver):
    driver.find_element(By.ID, "kw").send_keys("selenium")

At this time, no matter how many times the test case is run, the same debugging browser will be reused, and no new browser window will be opened.

Guess you like

Origin blog.csdn.net/lan_yangbi/article/details/127970162