#1. driver.window.handles 所有的窗口 ==== 列表 handles 就是id 每次都会变 # 最新打开的窗口在最末尾,最开始打开的窗口,在列表的第一值# 2. 选择最新窗口 window_handles[-1] # 3. 切换: driver.switch_to.window() / iframe /alert from selenium.webdriver.common.by import Byfrom selenium import webdriverfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ESfrom selenium.webdriver.common.by import Byimport time driver = webdriver.Chrome()driver.implicitly_wait(30) # 等待元素存在,命令执行完成 # 访问并搜索driver.get("http://www.baidu.com")driver.find_element_by_id("kw").send_keys("柠檬班")driver.find_element_by_id("su").click() # 条件loc = (By.XPATH,‘//a[text()="_腾讯课堂"]‘) # 我要找的元素# 获取点击之前的窗口总数wins = driver.window_handlesprint(wins[-1])#显性等待WebDriverWait(driver,30).until(ES.visibility_of_element_located(loc))# 点击元素driver.find_element(*loc).click() # 实现了新的窗口出现# 点击之后,会有两个窗口 有新窗口了。重新获取一次窗口列表,在切换到新窗口wins = driver.window_handlesWebDriverWait(driver,10).until(ES.new_window_is_opened(wins[-1])) time.sleep(2) # # 切换新窗口# wins = driver.window_handles# print(wins)# # 获取当前窗口的handles# current_win = driver.current_window_handle# # 切换到最新窗口# driver.switch_to.window(wins[-1])loc = (By.XPATH,‘//section[@class="section-main"]//h2[contains(text(),"老师")]‘)WebDriverWait(driver,30).until(ES.visibility_of_element_located(loc))driver.find_element(*loc).click() # ES.new_window_is_opened() # 回到主窗口啊driver.switch_to.window(wins[0])
原文地址:https://www.cnblogs.com/yago/p/11443680.html
时间: 2024-09-30 05:41:38