如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?


当前回答

Pynput是我发现的最好的解决方案,无论是Windows还是Mac。超级容易编程,工作得非常好。

例如,

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)

其他回答

Linux

from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()

来源:Python鼠标移动5行代码(仅适用于Linux)。

测试在WinXP, Python 2.6(3。在安装pywin32(在我的情况下是pywin32-214.win32-py2.6.exe)后:

import win32api, win32con
def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)

在屏幕上随机移动鼠标

它会根据你的屏幕分辨率在屏幕上随机移动鼠标。 检查下面的代码。

使用此命令安装pip Install pyautogui。

import pyautogui
import time
import random as rnd

#calculate height and width of screen
w, h = list(pyautogui.size())[0], list(pyautogui.size())[1]

while True:
    time.sleep(1)
    #move mouse at random location in screen, change it to your preference
    pyautogui.moveTo(rnd.randrange(0, w), 
                     rnd.randrange(0, h))#, duration = 0.1)

你可以使用win32api或ctypes模块来使用win32api来控制鼠标或任何gui

下面是一个使用win32api控制鼠标的有趣例子:

import win32api
import time
import math

for i in range(500):
    x = int(500+math.sin(math.pi*i/100)*500)
    y = int(500+math.cos(i)*100)
    win32api.SetCursorPos((x,y))
    time.sleep(.01)

使用ctypes进行单击:

import ctypes

# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up

尝试Clicknium, https://www.clicknium.com/documents/references/python/mouse/ 它可以控制鼠标和键盘,并帮助您定位web浏览器和桌面应用程序中的UI元素。

这是一个沿着圆圈移动鼠标的示例

from time import sleep
import math
from clicknium import clicknium as cc
def circle():
    a,b = cc.mouse.position()
    w = 20  
    m = (2*math.pi)/w 
    r = 200      

    while 1:    
        for i in range(0, w+1):
            x = int(a+r*math.sin(m*i))  
            y = int(b+r*math.cos(m*i))
            cc.mouse.move(x,y)
            sleep(0.2)

if __name__ == "__main__":
    circle()