如何在Python中自动粘贴文本?

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

在 Python 中,我一直在开发一个可用于 WhatsApp 的垃圾邮件机器人。运行脚本后,我会前往 WhatsApp Web,选择一个联系人,然后开始发送垃圾邮件。然而,我意识到

pyautogui.typewrite
对于较长的消息效果不佳,并且花费了更多时间,这并不能真正满足快速垃圾邮件发送的概念。因此,我认为粘贴完整消息可以使整个过程更快,而不是逐个字母地输入消息。

所以,这是最初的代码,运行良好,但无法快速输入:

import pyautogui as pt
import time

# Get the data for the spam
limit = input("Enter limit:")
message = input("Enter message:")

i = 0
time.sleep(5)

# loop until the limit is reached
while i < int(limit):
    pt.typewrite(message)
    pt.press("enter")
    i+=1

然后,我决定更改代码,使其粘贴而不是键入。因此,我将接收消息的行从

message = input("Enter message:")
更改为
clipboard.copy(input("Enter message:"))
。然后,我将输入消息的部分从
pt.typewrite(message)
更改为
pt.hotkey('command', 'v')
,它使用 Macbook 键盘快捷键 Command + V 来粘贴复制的文本。我也尝试过使用
clipboard.paste()
但没有任何作用。它并没有真正像预期的那样工作。你可以自己尝试一下代码,对我来说它没有按照我想要的方式工作:

import pyautogui as pt
import time
import clipboard

# Get the data for the spam
limit = input("Enter limit:")
clipboard.copy(input("Enter message:"))

i = 0
time.sleep(5)

# loop until the limit is reached
while i < int(limit):
    pt.hotkey('command', 'v')
    pt.press("enter")
    i+=1
python automation whatsapp pyautogui
1个回答
0
投票

这真的很复杂......但是如果剪贴板不起作用,您可以使用

pyautogui
手动复制并粘贴图像。 (这绝不是一个有效的答案,但这是我能想到的最好的答案)。

假设你从python的shell中获取垃圾邮件输入,我通过使用

pyautogui.locateCenterOnScreen()
找到了“:”冒号,以在shell中找到它。首先,在 python shell 中截取冒号“:”的屏幕截图,然后复制图像的路径。

接下来,编写这段代码:

import pyautogui

limit = input("Enter limit: ")

def get_cords():
    point = pyautogui.locateCenterOnScreen("path to picture of colon")
    return (point.x, point.y)

copy = input("Enter message: ")
point = get_cords()
point = (point[0] + 16, point[1])
pyautogui.moveTo(point)
pyautogui.drag(50, 0, button='right')
pyautogui.hotkey('ctrl', 'c')
#Copied text, paste wherever you need

这可能会起作用,尽管可能直到你做一些调整之后才会起作用。首先,您需要获取 python shell 中冒号图像的路径。其次,您需要测量输入文本框中冒号之间的距离。可能还会有其他调整。所有这一切...只是为了复制一个简单的单词。

其工作方式非常简单,但其代码比实际复杂得多。通常,当用户复制文本时,他们会单击并拖动以突出显示文本,然后通常使用键盘快捷键 ctrl+c/command+c 进行复制。这里,pyautogui 是手动完成的,但是要复杂得多,因为我们必须找到输入框中冒号的坐标,并进行大量的单击和拖动。

如您所见,这根本没有效率。由于

pyautogui
似乎对你有用,所以我建议这样做。我确实想指出,对于任何正在查看这个答案的人来说,这不是一个永久的解决方案。这应该只是暂时的,直到您解决安装问题为止。

© www.soinside.com 2019 - 2024. All rights reserved.