最近在做UI自动化 出现点击按钮复制文案到剪切板的操作 由于执行机器有mac、win10、liunx 出现不同的兼容问题 简单记录一下
1、常用获取方式 Python xerox模块import xerox xerox.copy(str) # 复制内容到剪切板 xerox.paste() # 读取剪切板内容 # Liunx可以选择粘贴到xsel中 xerox.copy(str, xsel True) xerox.paste(xsel True)Python pyperclip模块
import pyperclip pyperclip.copy(str) # 复制内容到剪切板 pyperclip.paste() # 读取剪切板内容命令行获取 Windows
复制 clip file.txt echo file.txt | clip clip file.txt # 写入文档 powershell -command Get-Clipboard # 直接输出到命令行Mac
复制 pbcopy file.txt cat file.txt | pycopy pbpaste file.txt # 写入文档 pbpaste # 直接输出到命令行Liunx
复制 到 gnome 的剪贴板 xsel file.txt cat file.txt | xsel xsel --input --clipboard # copy to clipboard xsel file.txt # 写入文档 xsel --output --clipboard # get from clipboardUbuntu
sudo apt-get install xclip # 需要先安装xclip 复制 到 gnome 的剪贴板 xclip -selection file.txt cat file.txt | xclip -selection xclip file.txt2、遇坑
由于UI自动化是selenium chrome 出现不兼容问题
2.1 macchrome页面模式/headless模式 均可正常获取
2.2 winchrome页面模式可以正常获取 headless模式不能写入系统剪切板
发现每次返回的都是上一次复制的内容使用xerox、pyperclip包均不可行尝试在用例执行过程中不停执行命令行 发现headless模式下不会将复制到的内容写入剪切板 2.3 centos无法获取系统剪切板
使用xerox包获取 获取到的剪切板内容为None使用命令行xsel --output --clipboard获取 仍然返回None使用pyperclip包报错PyperclipException:Pyperclip could not find a copy/paste mechanism for your system. 搜索需要安装xsel xclip 后续安装无果 解决方式作为英语渣渣熟练的command v复制文本到百度翻译 突然冒出一个想法“管你什么系统ctrl v粘贴没毛病” 开搞
from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutException self.driver.execute_script( window.open( ) ) # 打开一个新窗口 self.driver.switch_to.window(self.driver.window_handles[-1]) # 进入新窗口 self.driver.get(url https://fanyi.baidu.com/ ) # 访问百度翻译 exit True try: WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, desktop-guide-close ))) # 发现会有个广告弹窗 强制等待检查下是否出现弹窗 except TimeoutException: exit Flase if exit True: self.driver.find_element(*(By.CLASS_NAME, desktop-guide-close )).click() # 点击广告弹窗X按钮



