node.js - 如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本

标签 node.js puppeteer

有没有一种方法可以让我在nodejs中使用Puppeteer从浏览器剪贴板复制内容。我正在尝试复制页面呈现后的内容。这是通过以下代码实现的,但无法获取内容。

await page.keyboard.down('ControlLeft');
await page.keyboard.press('KeyA');
await page.keyboard.up('ControlLeft');

await page.keyboard.down('ControlLeft');
await page.keyboard.press('KeyC');
await page.keyboard.up('ControlLeft');

最佳答案

从输入框复制

您可以评估以下代码片段以从任何输入元素复制数据。

function copyText(selector) {
  var copyText = document.querySelector(selector);
  copyText.select();
  document.execCommand("Copy");
  return copyText.value;
}

用法:

const result = await page.evaluate(() => {
  function copyText(selector) {
    var copyText = document.querySelector(selector);
    copyText.select();
    document.execCommand("Copy");
    return copyText.value;
  }
  return copyText("#foo");
});

现在结果应该包含从输入框中复制的文本。

将任何内容复制到剪贴板

您可以评估 this answer 中的代码片段。

const result = await page.evaluate(() => {
  function copy(text) {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input)
  }
  return copy(document.body.innerHTML); // copy whatever want to copy
});

它将创建一个输入元素,将您提供的文本设置为值,然后从该元素复制数据,最后在使用后将其删除。

关于node.js - 如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49131516/

相关文章:

使用正则表达式的 Html 选择器

node.js - 语法错误: Cannot use import statement outside a module using puppeteer

node.js - 如何在 Node.js Puppeteer Headless=false Chromium 浏览器中清除历史记录(清除浏览数据)

node.js - 无法找到一种简单的方法来摆脱每个 Node js 的多个异步(sails)

node.js - 为单个 Controller 在 NestJs 上设置请求正文大小限制

node.js - 使用 Express 从 ASP.NET Web API 迁移到 Node.js

node.js - Nodejs 在创建一天后检查并更新数据库字段

selenium - 登录网站时如何使用 puppeteer/selenium 重用保存的凭据/密码?

javascript - Body-Parser 不读取请求正文

puppeteer - 获取 "TimeoutError: waiting for Page.printToPDF failed"时如何增加 pupetteer 的 Page.pdf 的超时?