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

puppeteer howto find element within parent element

cypress 我可以找到子元素 within 元素如下:

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

Puppeteer 是否与 within() 等价?

谢谢!

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

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

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

// 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');

您可以将 waitForFunction 方法与辅助方法一起使用:

const getChildElement = (handle, selector, options = {}) => {
  const node = handle.querySelector(selector)

  if (!node) return null

  if (options.text && !node.textContent.replace(/\s+/g, ' ').trim().includes(options.text)) {
    return null
  }

  // other checks...

  return node
}

const container = await page.$('#container')
page.waitForFunction(getChildElement, {}, container, '.child', {text: 'Text'})