【问题标题】:How to find document.activeElement in Puppeteer如何在 Puppeteer 中找到 document.activeElement
【发布时间】:2019-12-22 16:12:32
【问题描述】:

我想用 puppeteer 自动填写表格。 我填写第一个输入,然后单击一个按钮,然后创建一个具有焦点的新输入字段。

如何选择此输入?我可以使用 document.activeElement 吗?

  let newActivity = 'button.new_activity'
  await page.waitForSelector(newActivity)
  await page.click(newActivity)

// find active/focused input
await page.type(focusedInput, 'message')

【问题讨论】:

    标签: javascript node.js puppeteer autofill webautomation


    【解决方案1】:

    您可以使用evaluateHandle 获取元素句柄,然后对该元素调用type 函数。

    const el = await page.evaluateHandle(() => document.activeElement);
    await el.type('message');
    

    【讨论】:

      【解决方案2】:
      function findFocusedNode(node) {
          if (node.focused) {
              return node;
          }
      
          for (const child of node.children || []) {
              const focusedNode = findFocusedNode(child);
              if (focusedNode) {
                  return focusedNode;
              }
          }
      }
      
      const snapshot = await page.accessibility.snapshot();
      const focusedNode = findFocusedNode(snapshot);
      console.log('focusedNode', focusedNode);
      

      https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-accessibility

      【讨论】:

        猜你喜欢
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 2020-06-26
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        • 1970-01-01
        相关资源
        最近更新 更多