python+playwright learning-29 how to judge whether an element exists

foreword

How does playwright determine whether an element exists?

locator positioning element

Use the locator to locate the element, no matter whether the element exists or not, it will return a locator object, you can use the count() method to unify the number of elements, if the number of elements is 0, then the element does not exist

"""
判断元素存在
# 上海悠悠 wx:283340479  
# blog:https://www.cnblogs.com/yoyoketang/
"""
from playwright.sync_api import sync_playwright

with sync_playwright() as pw:
    browser = pw.chromium.launch()
    page = browser.new_page()

    page.goto("https://www.baidu.com/")

    # 元素存在
    loc1 = page.locator("id=kw")
    print(loc1)
    print(loc1.count())

    # 元素不存在
    loc2 = page.locator('id=yoyo')
    print(loc2)
    print(loc2.count())

operation result

<Locator frame=<Frame name= url='https://www.baidu.com/'> selector='id=kw'>
1
<Locator frame=<Frame name= url='https://www.baidu.com/'> selector='id=yoyo'>
0

The locator is used to locate the elements on the current page, and it will not wait automatically. If it is used in combination with click and other methods, it will automatically wait for the element to be in a clickable state.

query_selector positioning

ElementHandle represents an in-page DOM element. ElementHandles can be created using the page.query_selector() method.
The difference between Locator and ElementHandle is that the latter points to a specific element, whereas Locator captures the logic of how to retrieve that element.

If the element exists, return the element handle; if the element does not exist, return None


    # 元素存在
    loc1 = page.query_selector('#kw')
    print(loc1)  # JSHandle@node

    # 元素不存在
    loc2 = page.query_selector('#yoyo')
    print(loc2)  # None

You can also use the query_selector_all plural positioning method to return a list

    # 元素存在
    loc1 = page.query_selector_all('#kw')
    print(loc1)  # [<JSHandle preview=JSHandle@node>]

    # 元素不存在
    loc2 = page.query_selector_all('#yoyo')
    print(loc2)  # []

Guess you like

Origin blog.csdn.net/qq_27371025/article/details/129766836