Playwright-如何通过 ID 或名称选择元素?

问题描述 投票:0回答:1

Playwright-如何通过 ID 或名称选择元素?

我尝试使用剧作家中的 id 或名称来识别元素,但剧作家会抛出错误: “解析选择器名称=startcreateddate时未知引擎“名称” 创建Stackless”

playwright.$("name=startcreateddate")

python automation automated-tests playwright playwright-python
1个回答
0
投票

我猜您正在尝试选择类似于以下示例中的元素,并在由 Playwright Python 脚本(基于您的标签)启动的调试会话期间在浏览器控制台中执行此操作。

选择具有 id 的元素:

<p id="foo">hello</p>

使用

playwright.$("#foo")

选择具有

name=
属性的元素:

<input name="startcreateddate">

使用

playwright.$('[name="startcreateddate"]')

这是一个完整的可运行示例(您可以在浏览器控制台在断点处暂停时将上述命令粘贴到浏览器控制台中):

from playwright.sync_api import expect, sync_playwright


html = """<!DOCTYPE html><html><body>
<p id="foo">hello</p>
<input name="startcreateddate" value="world">
</body></html>"""


def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.set_content(html)

        page.pause() # paste the code above into the browser console

        # just in case you want to see these selectors in Python...
        p = page.locator("#foo")
        date = page.locator('[name="startcreateddate"]')

        print(p.text_content())
        print(date.get_attribute("value"))

        expect(p).to_have_text("hello")
        expect(date).to_have_value("world")

        browser.close()

if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.