Python selenium closes and switches the browser tab
1. Close all tabs of the browser
driver.quit()
2. Close the current tab (open a new tab B from tab A, close tab A)
driver.close()
3. Close the current tab (open a new tab B from tab A, close tab B)
You can use the browser's built-in shortcut to close the open tab
The shortcut keys of Firefox itself are:
Ctrl+t New tab
Ctrl+w close tab
Ctrl+Tab /Ctrl+Page_Up locate the next tab page of the current tab page
Ctrl+Shift+Tab/Ctrl+Page_Down locate the previous tab page of the current tab page
Ctrl+[number key 1-8] locate the first [1-8] of all tabs
Ctrl+number 9 to locate the last tab
Note: If you are in some Linux distribution systems, such as Ubuntu, you need to replace the Ctrl key with the Alt key
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
New tab
ActionChains(browser).key_down(Keys.CONTROL).send_keys("t").key_up(Keys.CONTROL).perform()
Close tab
ActionChains(browser).key_down(Keys.CONTROL).send_keys("w").key_up(Keys.CONTROL).perform()
4. Tab switching
from selenium import webdriver
browser=webdriver.Firefox()
browser.get('xxxxx')
Get the current window handle (window A)
handle = browser.current_window_handle
Open a new window
browser.find_element_by_id('xx').click()
Get all current window handles (window A, B)
handles = browser.window_handles
Traverse the window
for newhandle in handles:
Filter the newly opened window B
if newhandle!=handle:
Switch to the newly opened window B
browser.switch_to_window(newhandle)
Operate in the newly opened window B
browser.find_element_by_id('xx').click()
Close the current window B
browser.close()
Switch back to window A
browser.switch_to_window(handles[0])