python与selenium使用chrome浏览器在函数内调用该函数后浏览器自动关闭问题

时间:2021-07-22
本文章向大家介绍python与selenium使用chrome浏览器在函数内调用该函数后浏览器自动关闭问题,主要包括python与selenium使用chrome浏览器在函数内调用该函数后浏览器自动关闭问题使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

test.py

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
# 搜索输入框
search_input = driver.find_element_by_id("kw")
# 搜索selenium
search_input.send_keys("selenium")
# 搜索按钮
search_button = driver.find_element_by_id("su")
# 点击搜索按钮
search_button.click()

浏览器窗口不会自动关闭

elementLocator.py

from selenium import  webdriver
import time
class elementLocator():
  
    def __init__(self):
        self.driver= webdriver.Chrome()
        self.driver.get("http://www.baidu.com")
        self.driver.maximize_window()
   
 #xpath定位
    def elementLocator_xpath(self):
        #定位到登录按钮
        login_button = self.driver.find_element_by_xpath("//a[@id='s-top-loginbtn']") #相对定位
        #login_button = self.driver.find_element_by_xpath("/html/body/div/div/div[4]/a") #绝对定位(不建议)
        #点击登录按钮
        login_button.click()

elementLocator().elementLocator_xpath()

结果:浏览器自动关闭

原因:在函数内执行的浏览器操作,在函数执行完毕之后,程序内所有的步骤都结束了,关于这段程序的进程也就结束了,浏览器包含在内;如果将浏览器全局后,打开浏览器不在函数内部,函数里面的程序执行完是不会关闭浏览器的。

解决方法:

设置option.add_experimental_option("detach", True)不自动关闭浏览器
from selenium import  webdriver
import time
class elementLocator():
    def __init__(self):
        # 加启动配置
        option = webdriver.ChromeOptions()
        # 关闭“chrome正受到自动测试软件的控制”
        # V75以及以下版本
        # option.add_argument('disable-infobars')
        # V76以及以上版本
        option.add_experimental_option('useAutomationExtension', False)
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 不自动关闭浏览器
        option.add_experimental_option("detach", True)
        self.driver= webdriver.Chrome(chrome_options=option)
        self.driver.get("http://www.baidu.com")
        self.driver.maximize_window()

    #xpath定位
    def elementLocator_xpath(self):
        #定位到登录按钮
        login_button = self.driver.find_element_by_xpath("//a[@id='s-top-loginbtn']") #相对定位
        #login_button = self.driver.find_element_by_xpath("/html/body/div/div/div[4]/a") #绝对定位(不建议)
        #点击登录按钮
        login_button.click()
        time.sleep(4)
        self.driver.close()


elementLocator().elementLocator_xpath()

参考连接:https://blog.csdn.net/qq_43422918/article/details/97394705

原文地址:https://www.cnblogs.com/XiqueBlogs/p/15044383.html