Python+selenium(多表单、多窗口切换)

多表单切换

案例:在Frame.html文件种定位搜狗搜索页面,进行搜索操作

Frame.html

<html>
<head>
<title>Frame_test</title>
</head>

<body>
    <div>
        <iframe id="search" src="http://www.sogou.com" width="800" height="500">
    </div>
</body>

<html>

浏览器打开:

frame_test.py

from selenium import webdriver
from time import sleep

driver=webdriver.Firefox()
file_path=r'E:python_scriptWebdriver1.html'
driver.get(file_path)

# 切换到iframe(id="if")
driver.switch_to.frame('search')

driver.find_element_by_id("query").send_keys("python")
sleep(2)
driver.find_element_by_id("stb").click()
sleep(2)
driver.quit()

多表单切换,是通过switch_to.frame()方法将当前定位的主题切换为frame/iframe表单的内切页面中。

switch_to.frame()默认可以直接取表单的id或name属性。如果iframe没有可用的id和name属性,则可以通过下面的方式进行定位

# 先通过xpath定位到iframe
xf = driver.find_element_by_xpath('//*[@class="search"]')

# 再将定位对象传给switch_to.frame()方法
driver.switch_to.frame(xf)

多窗口切换

案例:在百度学术首页,点击注册按钮,进入注册页面,然后返回学术搜索页面,输入关键词搜索

 windows.py

from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://xueshu.baidu.com/")

# 获得百度学术搜索窗口句柄
search_windows = driver.current_window_handle
sleep(2)

driver.find_element_by_link_text('注册').click()
sleep(2)

# 获得当前所有打开的窗口的句柄
all_handles = driver.window_handles

# 进入注册窗口
for handle in all_handles:
    if handle!=search_windows:
        print('now is register window!')
        sleep(2)

# 回到学术搜索窗口
for handle in all_handles:
    if handle == search_windows:
        driver.switch_to.window(search_windows)
        sleep(2)
        print("now is search window!")
        driver.find_element_by_id('kw').send_keys('selenium')
        driver.find_element_by_id('su').click()
        sleep(2)

driver.quit()

webdriver提供了switch_to.window()方法,可以实现在不同的窗口之间切换。

在本案例中,涉及到的方法如下:

current_window_handle:获得当前窗口句柄

window_handles:返回所有窗口的句柄到当前会话

原文地址:https://www.cnblogs.com/NancyRM/p/8214413.html