(12)python+playwright自动化测试-iframe-中
1.简介
用实际的例子进行iframe自动化测试。经过长时间的查找,终于找到了一个含有iframe的网页(QQ邮箱和163邮箱),别的邮箱就没有细看了。所以这一篇的主要内容就是用这两个网页的iframe结合上一篇的理论知识,演示一下。
2.QQ邮箱
2.1iframe
F12查看HTML元素可以发现iframe,如下图所示:
2.2代码设计
2.3参考代码
from playwright.sync_api import Playwright, sync_playwrightdef run(playwright: Playwright) -> None:browser = playwright.chromium.launch(headless=False, slow_mo=1000)context = browser.new_context()page = context.new_page()page.goto("https://mail.qq.com/")page.wait_for_timeout(3000)#点击QQ登录page.locator("#QQMailSdkTool_login_loginBox_tab_item_qq").click()page.wait_for_timeout(3000)# 定位frameframe = page.frame_locator('[class="QQMailSdkTool_login_loginBox_qq_iframe"]').frame_locator("#ptlogin_iframe")#点击密码登录frame.locator("#switcher_plogin").click()frame.locator('#u').fill('程序员的世界你不懂')frame.locator('#p').fill("123456")frame.locator('#login_button').click()context.close()browser.close()with sync_playwright() as playwright:run(playwright)
2.4运行代码
1.运行代码,右键Run'Test',控制台输出,如下图所示:
3.163邮箱
3.1iframe
同理F12查看HTML元素可以发现iframe,如下图所示:
3.2代码设计
由于iframe 元素 id 属性是动态可变的id="x-URS-iframe1676960382133.3657"
可以使用xpath的contains 模糊匹配,或者css的正则匹配来对其进行定位。
3.3参考代码
from playwright.sync_api import Playwright, sync_playwrightdef run(playwright: Playwright) -> None:browser = playwright.chromium.launch(headless=False, slow_mo=1000)context = browser.new_context()page = context.new_page()page.goto("https://mail.163.com")# xpath 模糊匹配frame = page.frame_locator('//iframe[contains(@id, "x-URS-iframe")]')frame.locator('[name="email"]').fill('程序员的世界你不懂')frame.locator('[name="password"]').fill("123456")frame.locator('#dologin').click()context.close()browser.close()with sync_playwright() as playwright:run(playwright)
3.4运行代码
1.运行代码,右键Run'Test',控制台输出,如下图所示:
4.小结
1.在Web UI自动化的测试中,如果一个元素定位不到,那么最大的可能定位的元素属性是在 iframe 框架中,iframe 是 html 中的框架,在 html 中,所谓框架就是可以在同一个浏览器窗口中显示不止一个页面,对不同页面进行嵌套。顺着定位元素往上找,查看是否有<iframe>标签,找到说明要定位此元素,需先定位到元素所在的iframe,然后再定位元素。
2.frame标签有frameset、frame、iframe三种,frameset跟其他普通标签没有区别,不会影响到正常的定位,而frame与iframe对Playwright定位而言是一样的,Playwright有一组方法对frame进行操作。
3.通常采用id和name就能够解决绝大多数问题。但有时候frame并无这两项属性,则可以用index和WebElement来定位:
index从0开始,传入整型参数即判定为用index定位,传入str参数则判定为用id/name定位
WebElement对象,即用frame_locator系列方法所取得的对象,我们可以用tag_name、xpath等来定位frame对象