复制到剪贴板问题 - 在 GitHub Actions 上运行 Selenium Headless 浏览器

问题描述 投票:0回答:1

这是我添加到剪贴板的代码:

def add_to_clipboard(text):
     try:
         pyperclip.copy(text)  # Copy the text to the clipboard using pyperclip
     except Exception as e:
         print(f"An error occurred while copying to clipboard: {e}")

当我在本地运行它时,它在非无头浏览器上运行完美。但是,当我通过 GitHub actions 运行它时,它不起作用,因为 GitHub actions 似乎只能在无头浏览器上运行。

我该如何解决这个问题? 让我的代码在 GitHub Actions 上运行容易吗? 我应该使用 GitHub Actions 之外的东西吗?

来自 GitHub 的错误代码如下:

An error occurred while copying to clipboard: 
    Pyperclip could not find a copy/paste mechanism for your system.
    For more information, please visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error 
(Session info: chrome-headless-shell=124.0.6367.60)

我尝试在 python 中复制列表,以便能够使用 Selenium 将数据粘贴到网站中。我的解决方案在本地运行,但是,它不在 GitHub 操作上运行,因为它是无头浏览器。

我需要使剪贴板内容等于列表,以便我可以将表格数据粘贴到页面上。

python selenium-webdriver github-actions clipboard pyperclip
1个回答
0
投票

解决该问题的另一种方法是使用 JS Clipboard API。您可以使用

writeText()
将列表添加到剪贴板,并使用
readText()
将剪贴板的内容写入输入元素。

navigator.clipboard.writeText('Here, you add the content which will be copied!')
  .then(() => {
    console.log('Text copied to clipboard');
  })
  .catch((error) => {
    console.error('Error copying text to clipboard:', error);
  });

复制的内容可以使用下面的js片段在浏览器中使用

navigator.clipboard.readText()
    .then((e) => {
        console.log(e)
    })
    .catch((err) => {
        console.error(err)
    })

注意

  • 鉴于这些涉及 Promise,您需要异步执行 js。您可以在here
  • 发布的答案中阅读有关内容
  • 您需要添加您正在使用的浏览器的剪贴板功能
  • 您需要将焦点放在输入元素上才能使用剪贴板 API(出于安全目的,浏览器中禁止这样做)
© www.soinside.com 2019 - 2024. All rights reserved.