Selenium webdriver 自动关闭,我做错了什么?
我是学习 Selenium 的新手。我一直试图控制网页,让它自动关闭。我不明白这个问题。我尝试了很多在堆栈溢出上搜索的方法,也用谷歌搜索并阅读了 selenium 的文档。
from selenium import webdriver
chrome_driver_path = "D:\chromedirver.exe"
dirver = webdirver.Chrome(executable_path=chrome_driver_path)
driver.get("https://www.google.com")
经过一番研究,我更改了代码但遇到了同样的问题。
一些研究后的代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
chrome_driver_path = "D:\chromedriver.exe"
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://google.com")
Still B=浏览器自动关闭。
只需添加这两行
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver=webdirver.Chrome(executable_path=chrome_driver_path,chrome_options=options)
driver.get("https://www.google.com")
你的selenium脚本导致浏览器自动关闭的原因是因为它已经到了执行结束。该程序在执行最后一个功能后存在,即
driver.get("https://google.com")
完成。
如果您希望浏览器在程序执行后保留在屏幕上,您可以继续执行 Mohit Kumar 上面提到的操作,这基本上将您的浏览器从 python 程序的执行中分离出来。或者,您可以使用显式等待来查找 DOM 上的某些组件或使用
time.sleep()
函数来延迟程序的执行(不推荐)
使用 time.sleep() :
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://google.com")
sleep(30)
使用显式等待:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://google.com")
element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name=q]")))