Two 5‑Line Python Projects: Prevent Screen Sleep and Scrape Table Data
This tutorial demonstrates two concise Python projects—using pyautogui to keep the computer awake by moving the mouse and employing pandas to scrape tabular data from a website—each implemented with roughly five lines of code and explained step by step.
Python is praised for its elegance and ease of entry, and with just a few lines of code you can create useful utilities. This article introduces two playful projects that each require about five lines of Python.
Project 1 – Keep the Computer from Sleeping
The idea is to simulate mouse movement so the operating system thinks the user is active. The pyautogui library provides the moveRel(x, y) function for relative mouse moves, and the random.randint function generates random offsets.
pip install pyautogui # Import libraries
import pyautogui
import random
import time
while True:
x = random.randint(-200, 200)
y = random.randint(-200, 200)
pyautogui.moveRel(x, y)
time.sleep(5) # pause to avoid over‑loading the mouseThis simple loop continuously nudges the cursor, preventing the screen saver from activating.
Project 2 – Scrape Table Data with Five Lines
The second example shows how to fetch tabular data from the “中商情报网” website using pandas.read_html . The target table is the fourth one on the page (index 3), and the script iterates over the first ten pages, appending each result to a CSV file.
# Import libraries
import pandas as pd
import csv
for i in range(1, 10): # scrape pages 1‑9
tb = pd.read_html(f'http://s.askci.com/stock/a/?reportTime=2021-03-31&pageNum={i}')[3]
tb.to_csv(r'上市公司.csv', mode='a', encoding='utf_8_sig', header=1, index=0)The [3] index selects the desired table when multiple tables are present, and tables[x] can be used to choose any specific table.
Both projects illustrate how a few lines of Python can automate everyday tasks and serve as a springboard for deeper exploration of automation, data collection, and analysis.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.