欢迎来到魔幻小生的博客

selenium 多窗口处理、frame处理、多浏览器处理

多窗口处理

  • 点击某些链接,会重新打开⼀个窗口,想在新页⾯操作就得先切换窗口。

  • 获取窗口的唯⼀标识⽤句柄表⽰,通过切换句柄可以在多个页⾯灵活操作。

多窗口处理流程

  • 先获取当前窗口的句柄 driver.current_window_handle

  • 再获取所有的窗口句柄 driver.windows_handles

  • 判断当前窗口是否为需要操作的窗口,如果是,则在当前窗口进行操作;如果不是则切换到下一个窗口 driver.switch_to.window

def test_window(self):
	'''
	打开百度,点击登录,点击注册,跳转到注册页面输入用户名,再跳转到原页面输入用户名
	'''
	self.driver.get('http://www.baidu.com')
	self.driver.find_element(By.LINK_TEXT, '登录').click()
	self.driver.find_element(By.ID, 'TANGRAM__PSP_11__regLink').click()
	windows = self.driver.window_handles
	self.driver.switch_to.window(windows[-1])
	self.driver.find_element(By.ID, 'TANGRAM__PSP_4__userName').send_keys('username')
	time.sleep(3)
	self.driver.switch_to.window(windows[0])
	self.driver.find_element(By.NAME, 'userName').send_keys('username')
	time.sleep(3)

Frame 处理

在web自动化中,如果一个元素始终无法定位,那么很有可能是在 frame 中。

什么是 frame ?

  • frame 是 html 中的框架,所谓框架就是可以在同一个浏览器中显示不止一个页面。

  • 基于 html 框架,又可以分为垂直框架和水平框架(cols, rows)

Frame 分类:

  • frame标签分为 frameset、 ifame、 frame三种

  • frameset 和普通的标签一样,不会影响正常的元素定位,可以使用 index、 id、 name、 webelement 等方式定位到 frame

  • frame、 iframe 相当于 selenium 而言,则需要进行一些特殊的操作后,才能到定位到元素

演示:https://www.w3school.com.cn/tiy/t.asp?f=html_frame_cols

<html>
<frameset cols="25%, 50%, 25%">
	<frame src="/example/html/frame_a.html">
    <frame src="/example/html/frame_b.html">
    <frame src="/example/html/frame_c.html">
</frameset>
</html>

image

frame存在两种

  • 一种嵌套的

  • 一种未嵌套的

切换frame

  • driver.swich_to.frame():根据元素id、index切换frame

  • driver.switch_to.default_content():切换到默认frame

  • deiver.switch_to.parent_frame():切换到父级frame

处理未嵌套的frame

  • driver.switch_to.frame('frame的id'):有id时优先使用id

  • driver.switch_to.frame(frame-index'):没有id的时间根据索引来处理,索引从0开始

处理嵌套的frame

  • 对于嵌套的frame,则先进入到frame的父节点,再进到子节点,然后可以就可以子节点中的元素对象进行操作了

  • driver.switch_to.frame('父节点')

  • driver.switch_to.frame('子节点')

测试网站:https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable

打开测试网站,打印'请拖拽我'元素的文本,再打印'点击运行'元素的文本

image

我们如果直接用 find_element() 方法会报错,无法定位到元素。需要切换 frame。

    def test_frame(self):
        self.driver.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
        self.driver.switch_to.frame("iframeResult")
        print(self.driver.find_element(By.ID, 'draggable').text)
        self.driver.switch_to.default_content()
        print(self.driver.find_element(By.ID, 'submitBTN').text)

多浏览器处理

if env == 'firefox':
	self.driver = webdriver.firefox()
elif env == 'edge':
	self.driver = webdriver.edge()
else:
	self.driver = webdriver.Chrome()
posted @ 2025-07-11 23:47  魔幻小生  阅读(29)  评论(0)    收藏  举报