handles的操作

 1 # coding=utf-8
 2 # project:web自动化练习
 3 # date:2020/6/4
 4 # author:Victoria
 5 # file:do_handles.py
 6 # 主要是练习handles的操作
 7 from selenium import webdriver
 8 from selenium.webdriver.support.wait import WebDriverWait
 9 from selenium.webdriver.common.by import By
10 from selenium.webdriver.support import expected_conditions as EC
11 from time import sleep
12 
13 driver = webdriver.Firefox()
14 driver.get("https://www.baidu.com/")
15 
16 driver.find_element_by_id("kw").send_keys("柠檬班")
17 driver.find_element_by_id("su").click()
18 
19 WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@tpl='tieba_general']/h3/a")))
20 driver.find_element_by_xpath("//div[@tpl='tieba_general']/h3/a").click()
21 # 操作元素都等一等
22 sleep(0.5)
23 # 获取当前窗口的句柄
24 handles = driver.window_handles
25 print(handles)
26 # 打印当前窗口的句柄
27 print(driver.current_window_handle)
28 # 最后一个打开的界面为最新的界面
29 driver.switch_to.window(handles[-1])
30 
31 # 新的页面操作
32 # visibility_of_element_located里面是个元祖一定要记得价格括号
33 WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "j_head_focus_btn")))
34 driver.find_element_by_id("j_head_focus_btn").click()


方法2
使用new_window_is_opened
# coding=utf-8
# project:web自动化练习
# date:2020/6/4
# author:Victoria
# file:do_handles.py
# 主要是练习handles的操作
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.baidu.com/")

driver.find_element_by_id("kw").send_keys("柠檬班")
driver.find_element_by_id("su").click()

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@tpl='tieba_general']/h3/a")))
# 获取当前窗口的句柄
handles = driver.window_handles  # 窗口总数为1
# 操作,引起窗口的数量发生变化
driver.find_element_by_xpath("//div[@tpl='tieba_general']/h3/a").click()
# 等待新窗口出现
WebDriverWait(driver, 10).until(EC.new_window_is_opened(handles))
# 重新获取一下窗口
handles = driver.window_handles  # 窗口总数为1
# 最后一个打开的界面为最新的界面
driver.switch_to.window(handles[-1])

 




posted @ 2020-06-05 00:18  Albeexu  阅读(413)  评论(0编辑  收藏  举报