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


当前回答

另一种选择是使用跨平台AutoPy包。这个包有两个不同的选项来移动鼠标:

这段代码片段将立即将光标移动到(200,200)位置:

import autopy
autopy.mouse.move(200,200)

如果你想让光标在屏幕上移动到一个给定的位置,你可以使用smooth_move命令:

import autopy
autopy.mouse.smooth_move(200,200)

其他回答

如果你想移动鼠标,使用这个:

import pyautogui
pyautogui.moveTo(x,y)

如果你想点击,使用这个:

import pyautogui
pyautogui.click(x,y)

如果你没有安装pyautogui,你必须将python附加到CMD。进入CMD并输入:pip install pyautogui

这将为Python 2.x安装pyautogui。

对于Python 3。X,你可能不得不使用pip3 install pyautogui或python3 -m PIP install pyautogui。

非常容易 1-安装包:

pip install mouse

2-添加库到项目:

import mouse

3-举个例子:

mouse.right_click()

在这个url中描述所有你可以使用它的函数:

https://github.com/boppreh/mouse

快速和肮脏的函数,在Windows 7上使用ctypes库左键点击。无需下载。

import ctypes

SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event

def left_click(x, y, clicks=1):
  SetCursorPos(x, y)
  for i in xrange(clicks):
   mouse_event(2, 0, 0, 0, 0)
   mouse_event(4, 0, 0, 0, 0)

left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.

尝试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()

在屏幕上随机移动鼠标

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

使用此命令安装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)