1. 程式人生 > 其它 >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