puppeteer 如何在父元素中查找元素

mCY*_*mCY 4 node.js puppeteer

使用cypress我可以找到子元素within元素,如下所示:

cy.get('div#Login_form).within(() => {
  cy.get('input[name="human[email]"]').type('John')
  cy.get('input[name="human[password]"]').type('123456')
})
Run Code Online (Sandbox Code Playgroud)

Puppeteerfor有什么等价物within()吗?

谢谢!

AJC*_*C24 6

你可以做的一件事是声明你的 CSS 选择器路径,如下所示:

await page.type('div#Login_form > input[name="human[email]"]', 'John');
await page.type('div#Login_form > input[name="human[password]"]', '123456');
Run Code Online (Sandbox Code Playgroud)

另一种可能更容易阅读的替代方法(即使它确实意味着更多的代码行)是执行以下操作:

// Get the form element
const form = await page.$('div#Login_form');

// Get the email and password elements from the form
const email = await form.$('input[name="human[email]"]');
const password = await form.$('input[name="human[password]"]');

// Type the data into each element
await email.type('John');
await password.type('123456');
Run Code Online (Sandbox Code Playgroud)