跳到主要內容

Selectors

選擇器可以用於安裝自訂選擇器引擎。請參閱擴充性以了解更多資訊。


方法

註冊

在 v1.9 之前加入 selectors.register

選擇器必須在建立頁面之前註冊。

用法

註冊基於標籤名稱查詢元素的選擇器引擎範例

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
tag_selector = """
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},
// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"""

# Register the engine. Selectors will be prefixed with "tag=".
playwright.selectors.register("tag", tag_selector)
browser = playwright.chromium.launch()
page = browser.new_page()
page.set_content('<div><button>Click me</button></div>')

# Use the selector prefixed with its name.
button = page.locator('tag=button')
# Combine it with built-in locators.
page.locator('tag=div').get_by_text('Click me').click()
# Can use it in any methods supporting selectors.
button_count = page.locator('tag=button').count()
print(button_count)
browser.close()

with sync_playwright() as playwright:
run(playwright)

引數

  • name 字串#

    在選擇器中用作前綴的名稱,例如 {name: 'foo'} 啟用 foo=myselectorbody 選擇器。可能只包含 [a-zA-Z0-9_] 字元。

  • script 字串 (可選)#

    原始腳本內容。

  • content_script 布林值 (可選)#

    是否要在隔離的 JavaScript 環境中執行此選擇器引擎。此環境可以存取相同的 DOM,但無法存取框架腳本中的任何 JavaScript 物件。預設為 false。請注意,當此引擎與其他註冊引擎一起使用時,不保證作為內容腳本執行。

  • path Union[字串, pathlib.Path] (可選)#

    JavaScript 檔案的路徑。如果 path 是相對路徑,則會相對於目前的工作目錄解析。

傳回


set_test_id_attribute

加入於:v1.27 selectors.set_test_id_attribute

定義自訂屬性名稱,用於 page.get_by_test_id()。預設使用 data-testid

用法

selectors.set_test_id_attribute(attribute_name)

引數

  • attribute_name 字串#

    測試 ID 屬性名稱。