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 , driver version number , 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/")