【问题标题】:puppeteer howto find element within parent elementpuppeteer如何在父元素中查找元素
【发布时间】:2021-10-11 18:58:14
【问题描述】:

使用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() 是否有任何等价性?

谢谢!

【问题讨论】:

    标签: node.js puppeteer


    【解决方案1】:

    您可以做的一件事是声明您的 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');
    

    【讨论】:

    • Card-67110/11/2021
      我想从第二个跨度获取文本。我正在使用“div.MuiCardHeader-content > span[2]”选择器,我收到无效选择器错误。谁能帮我语法。
    • @Explorer 你不能在 CSS 选择器中使用数组索引。您需要做的是使用相当于querySelectorAll 的Puppeteers,然后按如下方式选择您的元素: const spanText = await page.$$eval('div.MuiCardHeader-content > span', (spans) =>跨度[1].textContent);
    • 我在使用你的代码后得到“1”作为输出,但是我们需要得到完整的日期,你能帮我得到完整的日期吗?
    【解决方案2】:

    您可以将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'})
    

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2016-12-24
      • 2016-04-25
      • 2020-04-25
      相关资源
      最近更新 更多