playwright判断元素是否存在
前言
我们在进行web自动化测试的过程中,有时候我们需要判断元素是否存在,才可以进行下一步的点击操作或断言,如果我们使用的是selenium,可以使用显式等待方式,或者使用find_elements判断列表长度,但是playwright有另外一个判断方式,直接计算元素数量来判断元素是否存在,比起selenium来说,步骤更为简单,本文就为大家介绍playwright判断元素是否存在的方法。
locator 定位元素
我们使用locator定位元素时,不论元素存不存在,都会返回一个locator 对象,所以我们可以使用count来计数,如果count不为0,则元素就存在,如果count为0,那元素就不存在。示例如下:
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com")
# 元素存在
loc1 = page.locator("id=kw")
print(loc1)
print(loc1.count())
# 元素不存在
loc2 = page.locator('id=muller')
print(loc2)
print(loc2.count())
with sync_playwright() as playwright:
run(playwright)
----------------------------------
输出结果如下:
<Locator frame=<Frame name= url='https://www.baidu.com/'> selector='id=kw'>
1
<Locator frame=<Frame name= url='https://www.baidu.com/'> selector='id=muller'>
0
注:locator 是定位当前页面上的元素,不会自动等待,如果用click等方法结合使用,会自动去等待元素处于可点击状态
query_selector 定位
ElementHandle 表示页内 DOM 元素。ElementHandles 可以使用page.query_selector()方法创建。
Locator和ElementHandle之间的区别在于后者指向特定元素,而 Locator 捕获如何检索该元素的逻辑。
元素存在返回元素句柄,元素不存在返回None,示例如下:
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com")
# 元素存在
loc1 = page.query_selector('#kw')
print(loc1)
# 元素不存在
loc2 = page.query_selector('#muller')
print(loc2)
with sync_playwright() as playwright:
run(playwright)
-------------------------------------------------
输出结果如下:
JSHandle@node
None
selenium可以使用find_elements来返回一个元素列表,playwright也可以使用query_selector_all 复数定位方式返回一个列表,示例如下:
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com")
# 元素存在
loc1 = page.query_selector_all('#kw')
print(loc1)
# 元素不存在
loc2 = page.query_selector_all('#muller')
print(loc2)
with sync_playwright() as playwright:
run(playwright)
----------------------------------------
输出结果如下:
[<JSHandle preview=JSHandle@node>]
[]
总结
本文主要介绍了playwright判断元素是否存在的方法,playwright对于元素是否存在的判断相比selenium更为直接。