简体   繁体   English

Selenium 4、自动关闭浏览器

[英]Selenium 4 and auto-closing browser

I have script on selenium 3 and it works fine:我在 selenium 3 上有脚本,它工作正常:

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:现在我为 selenium 4 重新设计了它,但现在浏览器在代码结束时自行关闭:

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:启动 chromedriver 时需要将“detach”选项设置为 True:

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.一种简单的方法是在代码末尾添加一个矮胖的input()

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.不要忘记将路径更改为 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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