将突出显示的文本复制到剪贴板,然后使用剪贴板将其追加到列表中

Сте*_*нов 4 python python-3.x pyautogui

我正在尝试使用适用于Python 3(Windows 10)的pyautogui模块自动化浏览器或文字处理器中的某些操作。

浏览器中有一个突出显示的文本。

text

以下脚本应打印突出显示的文本

import pyautogui as pya

# double clicks on a position of the cursor
pya.doubleClick(pya.position())

list = []
# a function copy_clipboard() should be called here
var = copy_clipboard()
list.append(var) 
print(list)
Run Code Online (Sandbox Code Playgroud)

输出应为:

[text]

那么函数copy_clipboard()应该是什么样的呢?谢谢您的帮助。

sou*_*ipe 6

键盘组合键Ctrl + C可以处理大多数应用程序中突出显示的内容,对您来说应该可以正常工作。这部分很容易使用pyautogui。对于编程获取剪贴板内容,如其他人所说,你可以用它实现ctypespywin32或者其他库。在这里,我选择了pyperclip

import pyautogui as pya
import pyperclip  # handy cross-platform clipboard text handler
import time

def copy_clipboard():
    pya.hotkey('ctrl', 'c')
    time.sleep(.01)  # ctrl-c is usually very fast but your program may execute faster
    return pyperclip.paste()

# double clicks on a position of the cursor
pya.doubleClick(pya.position())

list = []
var = copy_clipboard()
list.append(var) 
print(list)
Run Code Online (Sandbox Code Playgroud)


Muz*_*zol 5

使用 tkinter 的示例:

from tkinter import Tk
import pyautogui as pya

def copy_clipboard():
    root = Tk()     # Initialize tkinter
    root.withdraw() # hide the tkinter window
    pya.hotkey("ctrl", "c") # copy the text (simulating key strokes)
    clipboard = root.clipboard_get() # get the text from the clipboard
    return clipboard

copy_text = copy_clipboard()
print(copy_text)
Run Code Online (Sandbox Code Playgroud)

Tk().clipboard_get()返回剪贴板中的当前文本。