#coding=gbk ''' selenium多个窗口间切换 ''' from selenium import webdriver as wd from selenium.webdriver import ActionChains as AC from selenium.webdriver.common.keys import Keys import time import selenium.webdriver.support.ui as ui bc=wd.Chrome(executable_path='f:\chromedriver') bc.get('http://www.baidu.com') time.sleep(1) bc.find_element_by_id('kw').send_keys('w3school') AC(bc).send_keys(Keys.ENTER).perform() #记录当前窗口对象 now_handle=bc.current_window_handle time.sleep(3) #点击搜索结果的 w3chool 在线教程链接 #bc.find_element_by_partial_link_text('w3school').click() #动态获取网页加载完成 wait = ui.WebDriverWait(bc,10) wait.until(lambda bc:bc.find_element_by_xpath('//*[@id="1"]/h3/a')) bc.find_element_by_xpath('//*[@id="1"]/h3/a').click() time.sleep(5) #2个窗口间切换操作 for i in bc.window_handles: bc.switch_to.window(i) print(bc.title) #如果是新窗口,则操作 if bc.title!='w3school_百度搜索': try: wait.until(lambda bc:bc.find_element_by_link_text('HTML5')) bc.find_element_by_partial_link_text('HTML5').click() except: print('HTML5操作失败!!') time.sleep(3) bc.switch_to.window(now_handle) bc.find_element_by_id('kw').clear() bc.find_element_by_id('kw').send_keys('我是谁') AC(bc).send_keys(Keys.ENTER).perform()