Selenium 中使用 Python 時 close() 方法和 quit() 方法有哪些區別?
在有些情況下,我們需要用多個選項卡開啟不止一個瀏覽器。為了關閉這些會話,Selenium 中會用到 quit() 和 close() 方法。不過它們之間有區別,如下所列:
close() 方法可以關閉當前顯示的瀏覽器。而 quit() 方法配合使用 driver.dispose() 方法,它可以關閉每個後續視窗。
close() 方法關閉當前正在使用的視窗。而 quit() 方法會掛起所有驅動程式會話和例項,從而關閉每個已開啟的視窗。
示例
使用 close() 方法的程式碼實現。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com/windows") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Click Here").click() #to fetch the first child window handle chwnd = driver.window_handles[1] #to switch focus the first child window handle driver.switch_to.window(chwnd) #to close the first child window in focus driver.close()
使用 quit() 方法的程式碼實現。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com/windows") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Click Here").click() #to fetch the first child window handle chwnd = driver.window_handles[1] #to switch focus the first child window handle driver.switch_to.window(chwnd) #to close the all the windows driver.quit()
廣告