from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://bj.ganji.com/")
driver.implicitly_wait(5)
# 获取当前窗口句柄
h = driver.current_window_handle
# 打印当前窗口句柄
print(h)
driver.find_element_by_css_selector(".tabIcon.tabIcon-1").click()
all_h = driver.window_handles
# 打印所有句柄
print(all_h)
# 方法一:判断句柄,不等于首页就切换
# for i in all_h: # 这里不建议用for循环了,很多小伙伴懵的
# if i != h:
# driver.switch_to.window(i)
# print driver.title
# 方法二:获取list里面第二个直接切换
driver.switch_to.window(all_h[1])
print(driver.title)
# 关闭新窗口
driver.close()
# 切换到首页句柄
driver.switch_to.window(h)
print(driver.title)
原文:https://www.cnblogs.com/Tofuir-miss/p/13151516.html