Copy highlighted text to clipboard, then use the clipboard to append it to a list

耗尽温柔 提交于 2019-12-06 05:06:50

问题


I'm trying to automate some actions in a browser or a word processor with pyautogui module for Python 3 (Windows 10).

There is a highlighted text in a browser.

text

the following script should print the highlighted 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)

The output should be:

[text]

So how should the function copy_clipboard() look like? Thank you for your help.


回答1:


The keyboard combo Ctrl+C handles copying what is highlighted in most apps, and should work fine for you. This part is easy with pyautogui. For getting the clipboard contents programmatically, as others have mentioned, you could implement it using ctypes, pywin32, or other libraries. Here I've chosen 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)



回答2:


Well... Here it is:

from tkinter import Tk

def copy_clipboard():
    clipboard = Tk().clipboard_get()
    return clipboard

Tk().clipboard_get() returns the current text in the clipboard.

And you need to use pyautogui.hotkey('ctrl', 'c') first.




回答3:


What soundstripe posted is valid, but doesn't take into account copying null values when there was a previous value copied. I've included an additional line that clears the clipboard so null-valued copies remain null-valued:

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

def copy_clipboard():
    pyperclip.copy("") # <- This prevents last copy replacing current copy of null.
    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)



回答4:


You could import pyperclip and use pyperclip.copy('my text I want copied') and then use pyperclip.paste() to paste the text wherever you want it to go. You can find a reference here.



来源:https://stackoverflow.com/questions/51505304/copy-highlighted-text-to-clipboard-then-use-the-clipboard-to-append-it-to-a-lis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!