python+selenium元素定位04——浏览器多窗口处理

每个窗口都会产生一个独立的句柄、随机的字符串(由字母和数字组成),每次打开句柄值都会变化    

import os
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

current = os.getcwd()
chrome_driver_path =os.path.join(current,'../webdriver/chromedriver')
page_path = os.path.join(current,'../pages/element_samples.html') #本地html文件
driver = webdriver.Chrome(executable_path=chrome_driver_path)
driver.implicitly_wait(2)
driver.get('file://'+page_path)
handle =driver.current_window_handle
print('当前窗口handle值:',handle)
e =driver.find_element(By.XPATH,'//select[@name="jumpMenu"]')
Select(e).select_by_visible_text('开封教育网')
time.sleep(3)
handles =driver.window_handles #获得所有handle值
print('所有的handle值',handles)
driver.switch_to.window(handle) #切换到句柄为handle的窗口


##########简便法
for handle in driver.window_handles:
driver.switch_to.window(handle) #判断某句柄值,要在所有句柄值里,就移动到该句柄窗口页
if driver.title.__contains__('开封教育网'): #
break
time.sleep(1)
driver.quit()


####只要句柄和url
def switch_window_by_title(title):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.title.__contain__(title): #只要包含该标题,就切换到当前窗口
break

def switch_window_by_url(url):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.current_url.__contain__(url): #只要包含该url,就切换到当前窗口
break
原文地址:https://www.cnblogs.com/miaoxiaochao/p/12639981.html