I have an issue in selenium. With my code I should be able to click on an image and wait 3 seconds. In this process it opens several tabs. I don't know how to close these tabs.
This is my code:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome(executable_path=".\chromedriver.exe")
#
links = ["http://activeation.com/4W79",
"http://activeation.com/4W89",
"http://activeation.com/36ky",
"http://activeation.com/36X5",
"http://activeation.com/38QK",
"http://activeation.com/4VdE",
"http://activeation.com/4Vwm",
"http://activeation.com/4Vxi",
"http://activeation.com/4VyU",
"http://activeation.com/4Vza",
"http://activeation.com/4W0T"]
while True:
for link in links:
driver.get(link)
time.sleep(6)
element = driver.find_element_by_id("skip_bu2tton")
actionchains = ActionChains(driver)
actionchains.double_click(element).perform()
time.sleep(3)
答案 0 :(得分:0)
If several new windows/tabs might be opened after you navigate to new URL, you might need to use below code to close each window/tab except the base window:
# Define the base window
current = driver.current_window_handle
# Naviagte through list of URLs. No while loop needed
for link in links:
driver.get(link)
time.sleep(6)
driver.find_element_by_id("skip_bu2tton").click()
# Check each window
for window in driver.window_handles:
# If window is not a base window
if window != current:
# ...switch to that window...
driver.switch_to.window(window)
# ...close it...
driver.close()
# ...switch back to base window
driver.switch_to.window(current)