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

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

本文目录

playwright系列回顾

playwright连接已有浏览器操作

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

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

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

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

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

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

前文代码

直接定位指定浏览器

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]

启动新的浏览器

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()

悬浮元素定位

image-20230914152823495

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

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

定位方式一

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

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

定位方式二

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

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

定位方式三(推荐)

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

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

image-20230914160247093

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

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

自定义ID定位

官方方式

get_by_test_id

网页代码

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

<!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的值

直接定位指定浏览器

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()

启动新的浏览器

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()

我的实用方式

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() 组合在一起,以按标题和标签角色进行匹配。

button = page.get_by_role("button").and_(page.getByTitle("Subscribe"))

_or

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

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

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

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

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

# 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秒。

expect(page.get_by_text("梦无矶").last).to_be_visible(timeout=3000)

断言列表

AssertionDescription翻译
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 selectedSelect已选择选项
expect(page).to_have_title()Page has a titlepage有一个标题
expect(page).to_have_url()Page has a URLpage有一个URL
expect(api_response).to_be_ok()Response has an OK status响应状态为OK
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值