Python-selenium,切换句柄及封装

一、获取当前句柄及所有句柄

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()

 


posted @ 2020-05-03 22:01  安琪儿一直在  阅读(972)  评论(0编辑  收藏  举报