I have tried to identify the element using id or name in Playwright, but playwright throws an error:
"Unknown engine "name" while parsing selector name=startcreateddate createStackless"
.
My code is:
playwright.$("name=startcreateddate")
How can I select an element by Id or name in Playwright?
>Solution :
I’m guessing you’re trying to select elements that look something like those in the following example, and doing it in the browser console during a debug session initiated by a Playwright Python script (based on your tag).
For selecting an element with an id:
<p id="foo">hello</p>
use playwright.$("#foo")
.
For selecting an element with a name=
attribute:
<input name="startcreateddate">
use playwright.$('[name="startcreateddate"]')
.
The reason for the bizarre-looking error in your console is that foo=
syntax is used to set the selection engine, like text=
, css=
or xpath=
. name=
is not a valid engine option.
Here’s a complete runnable example (you can paste the above commands into the browser console when it pauses on the breakpoint):
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()