Python closes the browser in seconds after opening the browser with selenium-solution

When learning selenium, the first script found that after the browser was successfully opened, the browser closed after the code was executed. The code is as follows:

from  selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")

1. Check the code, there is no driver.quit() or driver.close() method written in the code, and there are no other error prompts;

2. Check the version number, browser version number 112.0.5615.121, driver version number 112.0.5615.49, and confirm that there is no problem with the version number;

3. Finally find a solution, as follows:

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_experimental_option('detach', True)

driver = webdriver.Chrome(options=options)
driver.get('http://www.baidu.com')

By default, python selenium will automatically close the browser after executing the code logic. The above code can prevent the browser from closing automatically.

Another easier way to write:

 

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

opt = Options()
opt.add_experimental_option('detach', True)
# 通过option参数,设置浏览器不关闭
web = Chrome(options=opt)
web.get("https://www.lagou.com/")

Guess you like

Origin blog.csdn.net/qq_40384309/article/details/130288762