==============================================
切换窗口
场景一:两个链接url在同一个窗口
from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
print(driver.title)
url2="http://jd.com"
driver.get(url2)
print(driver.title)
场景二:两个链接url在不同的窗口
from selenium import webdriver from time import sleep driver=webdriver.Chrome() driver.get("https://www.baidu.com") driver.maximize_window() print(driver.title) a="window.open('http://www.jd.com')" driver.execute_script(a) sleep(2)
场景三:多个窗口,title都是显示第一个
3.1
from selenium import webdriver from time import sleep driver=webdriver.Chrome() driver.get("https://www.baidu.com") driver.maximize_window() print(driver.title) a="window.open('http://www.jd.com')" driver.execute_script(a) sleep(2) print(driver.title) b="window.open('http://www.duoceshi.cn')" driver.execute_script(b) print(driver.title)
3.2定位其他窗口,报错现象
from selenium import webdriver
from time import sleep
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
print(driver.title)
a="window.open('http://www.jd.com')"
driver.execute_script(a)
sleep(2)
print(driver.title)
b="window.open('http://www.duoceshi.cn')"
driver.execute_script(b)
print(driver.title)
driver.find_element_by_link_text("行业资讯")
场景四:当两个窗口是切换窗口使用所有(0,和1)
from selenium import webdriver
from time import sleep
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
print(driver.title)
a="window.open('http://www.jd.com')"
driver.execute_script(a)
sleep(2)
print(driver.title)
# b="window.open('http://www.duoceshi.cn')"
# driver.execute_script(b)
print(driver.title)
j=driver.current_window_handle #获取当前窗口句柄
print(j)
handles=driver.window_handles #获取当前所有的句柄
print(handles)
driver.switch_to.window(handles[1])
print(driver.title)
# driver.find_element_by_link_text("行业资讯")
driver.find_element_by_link_text("你好,请登录").click()
场景五:for 循环去切换窗口
1、多个窗口:
from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
print(driver.title)
main_handle=driver.current_window_handle#保存主窗口的句柄,方便去了别的窗口之后切换回主窗口
driver.find_element_by_link_text("hao123").click()#新开一个“hao123”的窗口
js="window.open('https://www.taobao.com')"
driver.execute_script(js)#新开一个淘宝的窗口
all_handles=driver.window_handles #现在有3个handle,打比方我现在要切换到淘宝的那个窗口
for handle in all_handles:
driver.switch_to.window(handle)
if "淘宝" in driver.title:
break
print(driver.title)#检查是否在淘宝的窗口
driver.switch_to.window(main_handle)
print(driver.title)#检查是否已经切回了主窗口