前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【python自动化】Playwright基础教程(九)-悬浮元素定位&自定义ID定位&组合定位&断言

【python自动化】Playwright基础教程(九)-悬浮元素定位&自定义ID定位&组合定位&断言

作者头像
梦无矶小仔
发布2023-10-04 15:09:32
9760
发布2023-10-04 15:09:32
举报
文章被收录于专栏:梦无矶测开实录

playwright系列回顾

playwright连接已有浏览器操作

selenium&playwright获取网站Authorization鉴权实现伪装requests请求

【python自动化】playwright长截图&切换标签页&JS注入实战

【python自动化】Playwright基础教程(二)快速入门

【python自动化】Playwright基础教程(三)定位操作

【python自动化】Playwright基础教程(四)事件操作①元素高亮&元素匹配器

【python自动化】Playwright基础教程(五)事件操作②悬停&输入&清除精讲

【python自动化】Playwright基础教程(六)事件操作③单击&双击&计数&过滤&截图&JS注入

【python自动化】Playwright基础教程(七)Keyboard键盘

【python自动化】Playwright基础教程(八)鼠标操作

前文代码

「直接定位指定浏览器」

代码语言:javascript
复制
class Demo05:
    def __init__(self):
        """
        使用playwright连接谷歌浏览器
        :return:
        """
        self.playwright = sync_playwright().start()
        # 连接已经打开的浏览器,找好端口
        browser = self.playwright.chromium.connect_over_cdp("http://127.0.0.1:9223")
        self.default_context = browser.contexts[0]
        self.page = self.default_context.pages[0]

「启动新的浏览器」

代码语言:javascript
复制
class Demo06:
    def __init__(self, url):
        playwright = sync_playwright().start()
        browser = playwright.chromium.launch(headless=False)
        context = browser.new_context()
        self.page = context.new_page()
        self.page.goto(url)
       
        
if __name__ == '__main__':
    mwj = Demo05(url="指定的url")
    mwj.Locator_testid()

悬浮元素定位

当我们打开F12进行元素定位时,如果定位的是悬浮元素(有hover样式),鼠标想要定位是很恼火的。你上去,他出现,你要定位他不见。

这里我介绍三种方法,我经常使用的是第三种,前面两种作为了解即可。

定位方式一

  • 打开F12,鼠标悬浮在目标元素上
  • 单击鼠标右键,点击键盘上的N
  • 此时可以看到Elements已经快速定位到了目标元素。

「缺点」:你鼠标一动,元素定位就没了(气不气,气不气?!),元素定位我总不能去截图手打吧阿伟!

定位方式二

  • 打开F12,鼠标悬浮在目标元素上
  • 按下ctrl + shift + c
  • 此时可以看到Elements已经快速定位到了目标元素。

「缺点」:你鼠标一动,元素定位就没了(气不气,气不气?!),元素定位我总不能去截图手打吧阿伟!

定位方式三(推荐)

「优点」:你把鼠标点烂,把它从20楼丢下去,元素定位就在那,他不动,我说的偶像!

  • F12打开浏览器的调试页面
  • 点击源代码Sources
  • 右侧找到事件监听器断点(Event Listener breakpoints), 点开
  • 找到Mouse, 点开
  • 找到click,勾上

这时候你把鼠标悬浮到要定位的元素上,点击鼠标左键,这时候整个页面的事件就会被冻住,你就可以点回到Elements用定位方式进行定位,元素一直在那不会消失。

如果这次定位结束,那记得把刚刚勾选的内容取消掉,不然页面就一直在debug调试状态咯。

自定义ID定位

官方方式

「get_by_test_id」

「网页代码」

自己新建个html文件写入testID.html

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>点击变色</title>
    <style>
        #colorButton {
            width: 100px;
            height: 50px;
            background-color: red;
        }
    </style>
</head>
<body>
    <button id="colorButton" data-testid="xiaozai">梦无矶</button>

    <script>
        const colorButton = document.getElementById('colorButton');
        let isRed = true;

        function toggleColor() {
            if (isRed) {
                colorButton.style.backgroundColor = 'green';
                isRed = false;
            } else {
                colorButton.style.backgroundColor = 'red';
                isRed = true;
            }
        }

        colorButton.addEventListener('click', toggleColor);

        // 通过data-testid属性获取按钮
        const buttonWithTestId = document.querySelector('[data-testid="xiaozai"]');
        buttonWithTestId.addEventListener('click', toggleColor);
    </script>
</body>
</html>

上面代码实现的功能是,点击按钮变色,红色绿色交替,元素的属性为data-testid="xiaozai"

按照官方的方法来写python代码

第一步先要进行注册test_id,使用selectors.set_test_id_attribute

第二步用get_by_test_id进行定位这个id的值

「直接定位指定浏览器」

代码语言:javascript
复制
class Demo05:
    def __init__(self):
        """
        使用playwright连接谷歌浏览器
        :return:
        """
        self.playwright = sync_playwright().start()
        # 连接已经打开的浏览器,找好端口
        browser = self.playwright.chromium.connect_over_cdp("http://127.0.0.1:9223")
        self.default_context = browser.contexts[0]
        self.page = self.default_context.pages[0]
        
    def Locator_testid(self):
        self.playwright.selectors.set_test_id_attribute("data-testid")
        self.page.get_by_test_id("xiaozai").click()

「启动新的浏览器」

代码语言:javascript
复制
class Demo06:
    def __init__(self, url):
        playwright = sync_playwright().start()
        browser = playwright.chromium.launch(headless=False)
        context = browser.new_context()
        self.page = context.new_page()
        self.page.goto(url)
        
    def Locator_testid(self):
        self.playwright.selectors.set_test_id_attribute("data-testid")
        self.page.get_by_test_id("xiaozai").click()
        
if __name__ == '__main__':
    mwj = Demo05(url=r"file:///D:/L_Learning/MyLearningCode/learn_playwright/playwright_demo/testID.html")
    mwj.Locator_testid()

我的实用方式

代码语言:javascript
复制
class Demo05:
    def __init__(self):
        """
        使用playwright连接谷歌浏览器
        :return:
        """
        self.playwright = sync_playwright().start()
        # 连接已经打开的浏览器,找好端口
        browser = self.playwright.chromium.connect_over_cdp("http://127.0.0.1:9223")
        self.default_context = browser.contexts[0]
        self.page = self.default_context.pages[0]
        
    def Locator_testid(self):
        sself.page.locator("[data-testid='xiaozai']").click()

组合定位

_and

更新于1.34版本

方法 locator.and_() 通过匹配其他定位器来缩小现有定位器的范围。例如,您可以将 page.get_by_role() 和 page.get_by_title() 组合在一起,以按标题和标签角色进行匹配。

代码语言:javascript
复制
button = page.get_by_role("button").and_(page.getByTitle("Subscribe"))

_or

如果要定位两个或多个元素中的一个,并且不知道它将是哪个元素,请使用 locator.or_() 创建与任何替代元素匹配的定位器。

官方示列:您想单击“新电子邮件”按钮,但有时会显示安全设置对话框。在这种情况下,您可以等待“新电子邮件”按钮或对话框并采取相应措施。

代码语言:javascript
复制
new_email = page.get_by_role("button", name="New")
dialog = page.get_by_text("Confirm security settings")
expect(new_email.or_(dialog)).to_be_visible()

其他定位

官方文档:Other locators | Playwright Python

这些方式比较偏底层,适用于框架级别代码编写。

官方示列:点击某元素附近的元素

代码语言:javascript
复制
# Fill an input to the right of "Username".
page.locator("input:right-of(:text(\"Username\"))").fill("value")

# Click a button near the promo card.
page.locator("button:near(.promo-card)").click()

# Click the radio input in the list closest to the "Label 3".
page.locator("[type=radio]:left-of(:text(\"Label 3\"))").first.click()

断言

官方文档:https://playwright.dev/python/docs/test-assertions

如果你使用pytest结合的方式运行playwright,前提是下载了pytest-playwright库,可以进行相关的断言操作。

比如:断言页面上梦无矶元素是否可见,最长的等待时间为3秒。

代码语言:javascript
复制
expect(page.get_by_text("梦无矶").last).to_be_visible(timeout=3000)

断言列表

Assertion

Description

翻译

expect(locator).to_be_checked()

Checkbox is checked

复选框已被勾选

expect(locator).to_be_disabled()

Element is disabled

元素已被禁用

expect(locator).to_be_editable()

Element is editable

元素是可编辑的

expect(locator).to_be_empty()

Container is empty

容器为空

expect(locator).to_be_enabled()

Element is enabled

元素启用

expect(locator).to_be_focused()

Element is focused

元素被聚焦

expect(locator).to_be_hidden()

Element is not visible

元素不可见

expect(locator).to_be_visible()

Element is visible

元素可见

expect(locator).to_contain_text()

Element contains text

元素包含文本

expect(locator).to_have_attribute()

Element has a DOM attribute

元素有一个DOM属性

expect(locator).to_have_class()

Element has a class property

元素有一个class属性

expect(locator).to_have_count()

List has exact number of children

列表中有确切的子元素数目

expect(locator).to_have_css()

Element has CSS property

元素具有CSS属性

expect(locator).to_have_id()

Element has an ID

元素有一个ID

expect(locator).to_have_js_property()

Element has a JavaScript property

元素有一个JavaScript属性

expect(locator).to_have_text()

Element matches text

元素匹配文本

expect(locator).to_have_value()

Input has a value

输入有一个值

expect(locator).to_have_values()

Select has options selected

Select已选择选项

expect(page).to_have_title()

Page has a title

page有一个标题

expect(page).to_have_url()

Page has a URL

page有一个URL

expect(api_response).to_be_ok()

Response has an OK status

响应状态为OK

更多可以查看官方文档的操作。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-10-03 08:02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 梦无矶的测试开发之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前文代码
  • 悬浮元素定位
    • 定位方式一
      • 定位方式二
        • 定位方式三(推荐)
        • 自定义ID定位
          • 官方方式
            • 我的实用方式
            • 组合定位
              • _and
                • _or
                • 其他定位
                • 断言
                  • 断言列表
                  相关产品与服务
                  容器服务
                  腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档