Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Extract URLs from text with regex in Python
Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.
import re
text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""
url_pattern = r'https?://[^\s]+'
urls = re.findall(url_pattern, text)
for url in urls:
print(url)
How to Slugify a String in Python
Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.
import re
import unicodedata
def slugify(text):
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
text = re.sub(r'[^\w\s-]', '', text).strip().lower()
text = re.sub(r'[-\s]+', '-', text)
return text
if __name__ == "__main__":
title = "Hello, Worl…
Download Files from Internet with Progress Bar in Python
Download a file from the internet while displaying a text progress bar in the terminal.
import urllib.request
import sys
def download_with_progress(url, filename):
"""Download a file with a simple text progress bar."""
def report_hook(block_count, block_size, total_size):
downloaded = block_count * block_size
if total_size > 0:
percent = min(100, int(downloaded * 100 …
Extract Hyperlinks from Word Documents in Python
Parses a .docx file using Python's standard library to extract every hyperlink's display text and target URL.
import zipfile
from pathlib import Path
import xml.etree.ElementTree as ET
def extract_hyperlinks_from_docx(filepath: str) -> list[dict]:
"""
Extract all hyperlinks from a .docx file.
Returns a list of dicts with 'text' and 'target' keys.
"""
hyperlinks = []
with zipfile.ZipFile(Path(filepath)…
How to Fetch Weather Data from a Public API in Python
Fetches and parses weather data from a free public API using only the Python standard library.
import urllib.request
import json
def get_weather(city):
base_url = f"https://wttr.in/{city}?format=j1"
with urllib.request.urlopen(base_url) as response:
data = json.loads(response.read().decode())
current = data["current_condition"][0]
temp = current["temp_C"]
desc = current["weatherDesc…
How to Parse Query String to Dict with Duplicate Keys in Python
Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.
from urllib.parse import parse_qs
def parse_query_to_dict(query_string):
parsed = parse_qs(query_string, keep_blank_values=True)
return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}
if __name__ == "__main__":
query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
How to Serialize a Dictionary to a Query String in Python
Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.
import urllib.parse
def dict_to_query_string(params):
"""Serialize a dictionary to a URL query string."""
return urllib.parse.urlencode(params)
if __name__ == "__main__":
data = {
"name": "Alice Johnson",
"age": 30,
"city": "New York",
"interests": ["coding", "hiking"]
…
Aggregate Log Errors Count by Hour in Python
Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.
import re
from collections import Counter
from datetime import datetime
def aggregate_errors_by_hour(log_lines):
pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
hourly_counts = Counter()
for line in log_lines:
match = pattern.match(line)
if match:
ho…
Build a Complete Website Sitemap Generator Without External Services
Crawl a website recursively using only Python's standard library to generate a structured sitemap of internal links.
import json
from urllib.parse import urlparse, urljoin
from collections import deque
import urllib.request
import urllib.error
import re
from html.parser import HTMLParser
class SitemapParser(HTMLParser):
def __init__(self, base_url):
super().__init__()
self.base_url = base_url
self.links …
Build a Python Tool to Find All API Endpoints on a Website
A Python script that crawls a website, searches for common API endpoint patterns in HTML and JavaScript, and returns all discovered public API URLs.
import re
import requests
from urllib.parse import urljoin, urlparse
from collections import deque
def find_api_endpoints(base_url, max_pages=10):
visited = set()
queue = deque([base_url])
api_endpoints = set()
api_patterns = [
r'/api/[a-zA-Z0-9_/-]+',
r'/v[0-9]+/[a-zA-Z0-9_/-]+',…
Create a Python Script That Detects Website Technology Stack Automatically
This script sends an HTTP request to a URL and inspects headers and HTML content to identify technologies like servers, frameworks, and JavaScript libraries.
import requests
from re import search
def detect_tech_stack(url):
tech_stack = []
try:
response = requests.get(url, timeout=5, headers={'User-Agent': 'Mozilla/5.0'})
headers = response.headers
html = response.text.lower() if response.text else ''
# Check server header
…
Discover RSS Feeds From Any Website in Python
Scrape a website's HTML to automatically find all linked RSS or Atom feed URLs using requests, BeautifulSoup, and regex.
import requests
import re
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
def discover_rss_feeds(url):
"""Discover all RSS/Atom feeds linked from a given website."""
try:
headers = {'User-Agent': 'Mozilla/5.0 (compatible; RSSDiscovery/1.0)'}
response = requests.get(url…
Extract All Links from Any Website in Python
Scrape a webpage and extract all absolute HTTP/HTTPS links using requests and regex.
import requests
import re
from urllib.parse import urljoin
def extract_links(url):
try:
response = requests.get(url)
response.raise_for_status()
html = response.text
# Find all href attributes in anchor tags
pattern = r'href=["\'](.*?)["\']'
raw_links = re.findall(p…
Find All Redirects on a Website in Python
Crawl a website from a starting URL, follow links within the same domain, and detect every HTTP redirect (301, 302, 303, 307, 308) using requests with redirects disabled.
import requests
from urllib.parse import urljoin, urlparse
from collections import deque
def find_redirects(start_url, max_pages=50):
visited = set()
redirects = {}
queue = deque([start_url])
while queue and len(visited) < max_pages:
url = queue.popleft()
if url in visited:
…
Find Broken Image References Across a Website in Python
Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
def find_all_links(base_url, max_pages=50):
visited, to_visit = set(), {base_url}
while to_visit and len(visited) < max_pages:
url = to_visit.pop()
…
How to Automatically Download Every Favicon from a List of Websites in Python
Download each website's favicon.ico file by constructing its URL, making a GET request, and saving the binary content locally.
import requests
from urllib.parse import urlparse
import os
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.stackoverflow.com"
]
def download_favicon(url):
parsed = urlparse(url)
favicon_url = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
response = requests.g…
How to Check Website Status Codes in Python
This script checks the HTTP status codes of multiple URLs concurrently using a thread pool and prints the results.
import requests
from concurrent.futures import ThreadPoolExecutor
URLS = [
"https://www.google.com",
"https://www.python.org",
"https://www.nonexistent-site-12345.com",
"https://www.github.com",
]
def check_status(url):
try:
response = requests.get(url, timeout=5)
return url, resp…
How to Create a Link Graph Visualization for Any Website in Python
A Python script that crawls a website's internal links, builds a directed graph of parent-child URL relationships, and prints the graph to the console.
import requests
from bs4 import BeautifulSoup
from collections import defaultdict
from urllib.parse import urljoin, urlparse
import sys
def get_links(url, max_links=20):
try:
response = requests.get(url, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
base_url = f"{urlparse(u…
How to Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
How to Download a List of URLs to a Directory in Python
This script downloads a list of URLs into a specified directory, creating the folder if needed and keeping original filenames.
import urllib.request
from pathlib import Path
def download_urls(url_list, directory):
"""Download each URL in url_list into directory, keeping original filenames."""
save_dir = Path(directory)
save_dir.mkdir(parents=True, exist_ok=True)
for url in url_list:
filename = url.rstrip('/').spl…
How to Generate a QR Code in Python
Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.
import qrcode
# Data to encode
data = "https://www.example.com"
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code
img = qr.…
How to generate website performance reports from HTTP requests in Python
Measure and report website load time, status code, and content size using Python's standard library.
import urllib.request
import time
def measure_website_load_time(url):
"""Measures total loading time of a website."""
start_time = time.time()
try:
with urllib.request.urlopen(url, timeout=10) as response:
content = response.read()
status_code = response.status
…
Post a message to a Slack webhook in Python
Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.
import json
from urllib import request
def post_to_slack(webhook_url: str, message: str) -> dict:
payload = json.dumps({"text": message}).encode("utf-8")
req = request.Request(
webhook_url,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
wit…
How to Run a Mock Cron Pipeline Scheduler in Python
This code schedules a mock pipeline job to run every 2 seconds and hourly at :30 using the schedule library, then runs pending tasks for 10 seconds.
import time
import schedule
from datetime import datetime
def run_pipeline():
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Pipeline executed")
schedule.every(2).seconds.do(run_pipeline)
schedule.every().hour.at(":30").do(run_pipeline)
print("Scheduler started. Press Ctrl+C to stop.")
end_time = ti…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.