1 frame切换

1.1 切换到frame

wd.switch_to.frame(frame_reference)

其中,frame_reference可以是:

  1. frame元素的Id属性
  2. frame元素的name属性
  3. frame对应的WebElement对象

1.2 切回原来的主html

wd.switch_to.default_content()

1.3 示例

打开网址:https://cdn2.byhy.net/files/selenium/sample2.html,输出下图中所有的animal对象,然后点击“外部按钮“。
在这里插入图片描述

from selenium import webdriver
import time

# 创建Webdriver对象,指明使用Chromedriver,运行Chrome浏览器
wd = webdriver.Chrome()
wd.implicitly_wait(5)

# 调用Webdriver对象的get方法,打开网址
wd.get('https://cdn2.byhy.net/files/selenium/sample2.html')

# 方法一:根据frame的id属性值'frame1',切换到iframe中
wd.switch_to.frame('frame1')
# 方法二:根据frame的name属性值'innerFrame',切换到iframe中
wd.switch_to.frame('innerFrame')
# 方法三:根据frame对应的WebElement对象,切换到iframe中
wd.switch_to.frame(wd.find_element_by_css_selector('iframe'))

# 根据class name定位元素,并依次打印
elements = wd.find_elements_by_class_name('animal')
for element in elements:
    print(element.text)
    
# 切回最外部的HTML中
wd.switch_to.default_content()

# 定位外部按钮并点击
wd.find_element_by_css_selector('#outerbutton').click()

# 等待5秒
time.sleep(5)

# 关闭浏览器并释放进程资源
wd.quit()

2 窗口切换

2.1 切换新窗口

wd.switch_to.window(handle)

参数handle:操作窗口的句柄
WebDriver对象有window_handles属性,这是一个列表对象, 里面包括了当前浏览器里面所有的窗口句柄。所谓句柄,可以看成是对应网页窗口的一个ID,那么我们就可以通过类似下面的代码切换到对应的网页窗口:

for handle in wd.windao_handles:
	# 依次切换窗口
	wd.switch_to.window(handle)
	# 根据窗口的标题栏字符判断是否是我们要操作的那个窗口
	if 'XXX' in wd.title:
		# 如果是,那么这时候WebDriver对象就是对应的该窗口,跳出循环
		break

2.2 切回原来的窗口

# mainWindow变量保存当前窗口的句柄
mainWindow = wd.current_window_handle
...
# 通过前面保存的老窗口的句柄,切换到老窗口
wd.switch_to.window(mainWindow)

2.3 示例

打开百度,点击第一条百度热搜并在搜索结果新窗口中将搜索框中的文字清空,然后回到老窗口中输入“Selenium”。

from selenium import webdriver
import time

# 创建Webdriver对象,指明使用Chromedriver,运行Chrome浏览器
wd = webdriver.Chrome()
wd.implicitly_wait(5)

# 调用Webdriver对象的get方法,打开网址
wd.get("https://www.baidu.com/")

# mainWindow变量保存当前窗口的句柄
mainWindow = wd.current_window_handle

# 点击第一条热搜
hotSearch = wd.find_element_by_css_selector('span.title-content-title')
hotSearchTitle = hotSearch.text
hotSearch.click()

# 根据热搜标题切换到新窗口
for handle in wd.window_handles:
    wd.switch_to.window(handle)
    if hotSearchTitle in wd.title:
        break

# 清空新窗口中的输入框
wd.find_element_by_id('kw').clear()

# 切回老窗口
wd.switch_to.window(mainWindow)

# 输入框中输入‘Selenium'
wd.find_element_by_id('kw').send_keys('Selenium')

# 等待5秒
time.sleep(5)

# 关闭浏览器并释放进程资源
wd.quit()
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐