在 Python 版剧作家中,如何获取与 ElementHandle孩子、父母、祖父母、兄弟姐妹相关的元素?

问题描述

在 playwright-python 中,我知道我可以使用 elementHandle 获得 querySelector()

示例(同步):

from playwright import sync_playwright

with sync_playwright() as p:
    for browser_type in [p.chromium,p.firefox,p.webkit]:
        browser = browser_type.launch()
        page = browser.newPage()  
        page.goto('https://duckduckgo.com/')
        element = page.querySelector('input[id=\"search_form_input_homepage\"]')
    

如何根据此 elementHandle 获取与 this 相关的 an 元素? IE。父母、祖父母、兄弟姐妹、孩子处理?

解决方法

使用 querySelector() / querySelectorAllXPath (XML Path Language) 允许您检索 elementHandle(分别是句柄的集合)。一般来说,XPath 可用于浏览 XML 文档中的元素和属性。

from playwright import sync_playwright

with sync_playwright() as p:
    for browser_type in [p.chromium,p.firefox,p.webkit]:
        browser = browser_type.launch(headless=False)
        page = browser.newPage()
        page.goto('https://duckduckgo.com/')
        element = page.querySelector('input[id=\"search_form_input_homepage\"]')
        
        parent = element.querySelector('xpath=..')
        grandparent = element.querySelector('xpath=../..')
        siblings = element.querySelectorAll('xpath=following-sibling::*')
        children = element.querySelectorAll('xpath=child::*')

        browser.close()