一、獲取當前句柄及所有句柄
handle=driver.current_window_handle #獲取當前窗口句柄
print(handle)
handles=driver.window_handles #獲取所有窗口句柄
print(handles)
二、獲取指定句柄,並封裝成方法
#coding=gbk
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
curent_path=os.path.dirname(__file__)
driver=webdriver.Chrome()
page_path=os.path.join(curent_path,'./pages/element_samples.html')
driver.implicitly_wait(10)
driver.get('file://'+page_path)
handle=driver.current_window_handle #獲取當前窗口句柄
print(handle)
handles=driver.window_handles #獲取所有窗口句柄
print(handles)
##封裝
def switch_window_by_title(title):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.title.__contains__(title):
break
def switch_window_by_url(url):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.current_url.__contains__(url):
break
##小測試
e=driver.find_element(By.XPATH,'//select[@name="jumpMenu"]')
Select(e).select_by_visible_text("開封教育網")
# switch_window_by_title("開封市教育體育網") ##切換到這個句柄
switch_window_by_url('http://jtj.kaifeng.gov.cn/')
driver.find_element(By.XPATH,'//a[text()="政務服務"]').click()