Overview
This article explains how to use PyAutoGUI to scroll through web pages or long documents. In addition to basic vertical scrolling, we will cover horizontal scrolling, which is useful for spreadsheets. The key is understanding how positive and negative values change the direction.
Specifications
- Input: Scroll amount (integer: clicks), mouse cursor position (optional: x, y).
- Output: Scrolling action in the active window or the window under the mouse cursor.
- Prerequisite: The
pyautoguilibrary must be installed. Scrolling usually occurs in the window where the mouse cursor is currently located.
Basic Usage
This is the basic code for vertical scrolling. Positive values scroll “up,” and negative values scroll “down.”
import pyautogui
import time
# Preparation time
time.sleep(2)
# Scroll up (moving back to the top of a page)
pyautogui.scroll(500)
# Scroll down (moving down a page)
pyautogui.scroll(-500)
Full Code Example
The following demo code performs vertical and horizontal scrolling in a browser or editor. Note that horizontal scrolling only works in applications that support it.
import pyautogui
import time
def scroll_demonstration():
"""
Demo function to check vertical and horizontal scrolling.
Activate a scrollable window (like a browser) immediately after running.
"""
pyautogui.FAILSAFE = True
print("Starting scroll operations in 3 seconds...")
print("Please place the mouse cursor over the browser or editor.")
time.sleep(3)
try:
# 1. Vertical Scroll
# The number represents "clicks." Sensitivity depends on OS settings.
print("Scrolling down...")
for _ in range(3):
pyautogui.scroll(-300) # Negative value = Down
time.sleep(0.5)
print("Scrolling up...")
pyautogui.scroll(900) # Positive value = Up
time.sleep(1)
# 2. Horizontal Scroll
# Note: This may not work depending on the OS or app (mainly for Linux/macOS).
print("Attempting to scroll right...")
pyautogui.hscroll(100) # Positive value = Right
time.sleep(0.5)
print("Attempting to scroll left...")
pyautogui.hscroll(-100) # Negative value = Left
print("Operation completed.")
except KeyboardInterrupt:
print("Interrupted.")
if __name__ == "__main__":
scroll_demonstration()
Customization Points
Understanding Parameters
scroll(clicks, x=None, y=None)
- clicks (int): Specifies the scroll amount.
- Positive (+): Scrolls up (turning the wheel away from you).
- Negative (-): Scrolls down (turning the wheel toward you).
- x, y (int): If specified, the mouse moves to these coordinates before scrolling. This is helpful because the scroll signal is sent to the window under the cursor.
Horizontal Scrolling (hscroll)
pyautogui.hscroll(clicks) This performs horizontal scrolling. It is effective for wide screens like Excel.
- Positive: Scrolls right.
- Negative: Scrolls left.
Important Notes
Sensitivity Differences
The distance scrolled for 1 unit of clicks varies greatly depending on OS settings and applications. Some apps move only one line with “100,” while others move a full screen. Always test and adjust the values.
Mouse Cursor Position
If the screen does not scroll, the mouse cursor might be outside the target window. Use moveTo() or click() to make sure the target window is active before scrolling.
Horizontal Scrolling on Windows
hscroll() may not work (it might be ignored) on Windows. In such cases, you may need an alternative like holding the Shift key while scrolling (keyDown('shift') + scroll()).
Advanced Usage
The following function moves the mouse to specific coordinates and scrolls an element like a list box or chat log.
import pyautogui
import time
def scroll_target_area(target_x, target_y, amount):
"""
Moves the mouse to a specified position and scrolls the element there.
"""
pyautogui.FAILSAFE = True
# Move to the specified position (otherwise a different area might scroll)
pyautogui.moveTo(target_x, target_y, duration=0.5)
# Wait briefly to stabilize focus
time.sleep(0.2)
# Execute scroll
print(f"Scrolling {amount} at coordinates ({target_x}, {target_y})")
pyautogui.scroll(amount)
if __name__ == "__main__":
# Example: Scroll down near the center of the screen
w, h = pyautogui.size()
scroll_target_area(w // 2, h // 2, -500)
Conclusion
Basic scrolling with PyAutoGUI is done using scroll(amount). Remember that positive is up and negative is down. Since the scroll amount depends heavily on the environment, we recommend testing the behavior on your specific application and adjusting the values accordingly.
