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

后端 未结 5 998
刺人心
刺人心 2020-12-16 18:54

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.

相关标签:
5条回答
  • 2020-12-16 19:07

    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.

    0 讨论(0)
  • 2020-12-16 19:13

    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)
    
    0 讨论(0)
  • 2020-12-16 19:19

    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.

    0 讨论(0)
  • 2020-12-16 19:27

    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)
    
    0 讨论(0)
  • 2020-12-16 19:31

    Another option to get highlighted/selected text:

    import subprocess
    import shlex
    selected_text = subprocess.check_output((shlex.split('xclip -out -selection')))
    
    0 讨论(0)
提交回复
热议问题