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

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

本文目录

文章目录

  • 【python自动化】Playwright基础教程(九)-悬浮元素定位&自定义ID定位&组合定位&断言
    • playwright系列回顾
    • 前文代码
    • 悬浮元素定位
      • 定位方式一
      • 定位方式二
      • 定位方式三(推荐)
    • 自定义ID定位
      • 官方方式
      • 我的实用方式
    • 组合定位
      • _and
      • _or
    • 其他定位
    • 断言
      • 断言列表

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

悬浮元素定位

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

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

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

定位方式一

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

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

定位方式二

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

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

定位方式三(推荐)

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

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

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

这时候你把鼠标悬浮到要定位的元素上,点击鼠标左键,这时候整个页面的事件就会被冻住,你就可以点回到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)

断言列表

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

你可能感兴趣的:(playwright,python,playwright,自动化)