简体   繁体   中英

Selenium 4 and auto-closing browser

I have script on selenium 3 and it works fine:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('https://ya.ru/')
driver.find_element_by_name('text').send_keys('some text')
driver.find_element_by_class_name('search2__button').click()

Now i reworked it for selenium 4, but now browser closing on its own when code ends:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.maximize_window()
driver.get('https://ya.ru/')
driver.find_element(By.NAME, 'text').send_keys('some text')
driver.find_element(By.CLASS_NAME, 'search2__button').click()

I want to keep browser open.

I found this answer here .

You need to set the "detach" option to True when starting chromedriver:

from selenium.webdriver import ChromeOptions, Chrome
opts = ChromeOptions()
opts.add_experimental_option("detach", True)
driver = Chrome(chrome_options=opts)

One simple way would be to add a dumpy input() at the end of the code.

on_hold = input("Enter anything on the console to exit.")

Can you try this code out, it didn't auto close for me. Don't forget to change the path to the location of the chromedriver.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

ser = Service("path/to/chromedriver.exe")
op = webdriver.ChromeOptions()
driver=webdriver.Chrome(service=ser,options=op)

driver.maximize_window()
driver.get('https://ya.ru/')
driver.find_element(By.NAME, 'text').send_keys('some text')
driver.find_element(By.CLASS_NAME, 'search2__button').click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM