我尝试在 Playwright 中使用 id 或 name 来识别元素,但是 playwright 抛出错误:
"Unknown engine "name" while parsing selector name=startcreateddate createStackless"
.
我的代码是:
playwright.$("name=startcreateddate")
如何在 Playwright 中通过 ID 或名称选择元素?
我猜您正在尝试选择类似于以下示例中的元素,并在由 Playwright Python 脚本(基于您的标签)启动的调试会话期间在浏览器控制台中执行此操作。
选择具有 id 的元素:
<p id="foo">hello</p>
使用
playwright.$("#foo")
。
选择具有
name=
属性的元素:
<input name="startcreateddate">
使用
playwright.$('[name="startcreateddate"]')
。
出现奇怪错误的原因是
foo=
语法用于设置引擎,如css=
或xpath=
。不过,不鼓励这种做法。
这是一个完整的可运行示例(您可以在浏览器控制台在断点处暂停时将上述命令粘贴到浏览器控制台中):
from playwright.sync_api import expect, sync_playwright # 1.37.0
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()