In Python, to obtain the specific position and actions of the mouse on the screen and determine whether the mouse is in the browser, we can use the pyautogui library. pyautogui is a very powerful library that can be used to simulate mouse operations, screenshots, obtain screen size and resolution, etc.
Install pyautogui
First, make sure you have pyautogui installed. If you haven't installed it, you can install it via pip:
pip install pyautogui
Get the mouse position
You can use() to get the current position of the mouse. This function returns a tuple containing two elements, representing the X and Y coordinates of the mouse on the screen.
import pyautogui # Get the current mouse positionx, y = () print(f"Mouse position: X={x}, Y={y}")
Listen to mouse actions
pyautogui also allows you to listen for mouse events, such as mouse clicks, moves, etc. You can use the() method to achieve it. However, note that this method blocks your script until you stop listening manually. If you want to continuously listen in the background, you can consider using threads or asynchronous programming.
import pyautogui def on_move(x, y): print(f"Mouse moved to: X={x}, Y={y}") def on_click(x, y, button): print(f"Mouse clicked at: X={x}, Y={y}, Button={button}")
# Listen to mouse movement and click events(onMove=on_move, onClick=on_click)
Determine whether the mouse is in the browser
To determine whether the mouse is in the browser, you need to know the location and size of the browser window. You can use() to get window information for a specific title, and then determine whether the mouse position is within the area of this window.
import pyautogui # Assume that the title of the browser window is "Google Chrome"windows = ('Google Chrome') if windows: window = windows[0] # Get the first matching window, if there are multiple ones, select the first one x, y = () # Get the current mouse position # Get the position and size of the window window_x, window_y, width, height = , , , # Determine whether the mouse is in the browser window if window_x <= x <= window_x + width and window_y <= y <= window_y + height: print("Mouse is inside the browser.") else: print("Mouse is outside the browser.") else: print("Browser window not found.")
Notice:
Make sure your script has permission to access this information, especially on some operating systems that may require additional permissions.
For cross-platform compatibility, especially on Windows and MacOS, make sure your code works correctly on different platforms. For example, the properties and methods of windows may vary between platforms.
For more complex window management or automation tasks, consider using libraries like pywinauto (for Windows) or pyobjc (for MacOS) to provide more precise window control and event listening. But for simple tasks, pyautogui is already powerful enough and easy to use.
Method extension
Python get mouse shape and position
import win32gui cur = () print(cur) # The output is a tuple, similar to (1, 65561, (606, 699)) # in:# The second element is the shape code of the mouse# The third element is the mouse position # Mouse shape code:# 65539: Normal mouse shape#65541: Shape of text input#65555: Resize the shape of the window#65567: The finger head of the hyperlink#65543: Circles#65561: Normal mouse shape + circle# If you want to write a code that waits for the end of the mouse to circle, it should look like this:import win32gui import time while ()[1] == 65543: (1) print('End of a circle')
Use python to get the coordinates of the mouse on the screen
import pyautogui as pg import time def mouse_coordinate(): print('Press Ctrl-C to quit.') try: while True: # Get the x and y coordinates under the mouse x, y = () # Adjust the x, y output format positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end='') (0.2) print('\b' * len(positionStr), end='', flush=True) except KeyboardInterrupt: print('\nDone.') if __name__ == '__main__': mouse_coordinate()
python selenium gets mouse position
# Capture mouse movement events().() # After capturing the action that needs to be done after clicking, it is completed in the mouseover function, mainly extracting the coordinates of the pointfrom PySide2 import QtGui, QtWidgets, QtCore # from import QtCore import pyqtgraph as pg import sys from random import randint import numpy as np FieldRadius = 100 class MainWindow(): def __init__(self): super().__init__() ('pyqtgraph drawing') # Create a PlotWidget object = () # Set the chart title ("Node Distribution Map", color='008080', size='12pt') # Set up the labels up, down, left and right ("left","Dimensional coordinate") ("bottom","Horizontal") (min=0, # Minimum value max=FieldRadius) # Maximum value # Set Y-axis scale range (min=0, # Minimum value max=FieldRadius) # Maximum value # Show table line (x=True, y=True) # Change the background color to white ('w') # Center to display PlotWidget () # In real time, the PlotDataItem object should be obtained, and its setData method should be called. # This way, only replot the curve, and the performance is higher = (pen=None, symbol='o') = 0 = [] #The value of x-axis self.new_point_x = 0 = [] # The value of the y-axis self.new_point_y = 0 (False) ().() ().(self.mouse_clicked) # Start the timer and refresh the data every 1 second = () () (100) def updateData(self): (, ) # Mouse movement event, used to obtain exact coordinates (as if the coordinates of the mouse click are inaccurate) def mouseover(self,pos): # Parameter pos is pixel coordinates, which need to be converted into scale coordinates act_pos = (pos) if type(act_pos) != : return # print("over_1:",act_pos.x(), act_pos.y()) self.new_point_x = act_pos.x() self.new_point_y = act_pos.y() # Mouse click event, used to handle events after mouse click, including: # 1) Add new coordinates def mouse_clicked(self,event): (self.new_point_x) (self.new_point_y) # print("my position is:",,) if __name__ == '__main__': app = () main = MainWindow() () app.exec_()
This is the article about how to use Python to obtain the specific position and actions of the mouse on the screen. For more related content on Python to obtain the mouse position, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!