Here’s a little, self-contained Python script that
- Opens a CSV file that contains a list of URLs.
- Sends an HTTP GET request to each URL.
- Reports whether the server answered with status-code 200 (OK).
- Writes the results to stdout and (optionally) a new CSV file.
Feel free to copy-paste the code into a file called, say, url_checker.py.
#!/usr/bin/env python3
"""
url_checker.py
~~~~~~~~~~~~~~
Usage:
python url_checker.py input.csv # read URLs from 'input.csv'
python url_checker.py input.csv -o results.csv # also save results
The script expects a column named 'url' in the CSV.
If your column has a different name, pass -c "column_name".
"""
import argparse
import csv
import sys
from pathlib import Path
from typing import Iterable, Tuple
import requests
from requests.exceptions import RequestException
# -------------------------------------------------
# Utility functions
# -------------------------------------------------
def parse_args() -> argparse.Namespace:
ap = argparse.ArgumentParser(description="Check URLs from a CSV file.")
ap.add_argument("csv_file", help="Path to the CSV that contains URLs")
ap.add_argument(
"-c",
"--column",
default="url",
help='Column name that stores the URLs (default: "url")',
)
ap.add_argument(
"-o",
"--output",
help="Optional path to save a new CSV with the status codes",
)
ap.add_argument(
"-t",
"--timeout",
type=float,
default=10,
help="Request timeout in seconds (default: 10)",
)
return ap.parse_args()
def read_urls(csv_path: Path, column: str) -> Iterable[str]:
"""
Yield each URL from the given CSV. The CSV must have a header row.
"""
with csv_path.open(newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
if column not in reader.fieldnames:
sys.exit(f"⚠️ Column '{column}' not found in CSV header.")
for row in reader:
url = (row.get(column) or "").strip()
if url:
yield url
def check_url(url: str, timeout: float) -> Tuple[str, int]:
"""
Returns (url, status_code) – status_code will be:
200 : success
0 : any kind of problem (timeout, DNS failure, 4xx/5xx, etc.)
"""
try:
resp = requests.get(url, timeout=timeout, allow_redirects=True)
return url, resp.status_code
except RequestException:
return url, 0
def main() -> None:
args = parse_args()
csv_in = Path(args.csv_file)
if not csv_in.is_file():
sys.exit(f"❌ File '{csv_in}' does not exist.")
results = []
print(f"🔍 Checking URLs in {csv_in} …\n")
for url in read_urls(csv_in, args.column):
url, status_code = check_url(url, args.timeout)
ok = "✅" if status_code == 200 else "❌"
print(f"{ok} {url:<60} {status_code}")
results.append({"url": url, "status_code": status_code})
# Optional: write results to another CSV
if args.output:
out_path = Path(args.output)
with out_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["url", "status_code"])
writer.writeheader()
writer.writerows(results)
print(f"\n📄 Results saved to {out_path}")
if __name__ == "__main__":
main()
Instructions & notes
-
Install the only external dependency:
pip install requests
-
Prepare your input.csv. It just needs a column header called url (or any name you pass with -c). Example:
url
https://example.com
https://httpstat.us/404
https://httpstat.us/200
-
Run the script:
python url_checker.py input.csv -o checked.csv
Output (example):
🔍 Checking URLs in input.csv …
✅ https://example.com 200
❌ https://httpstat.us/404 404
✅ https://httpstat.us/200 200
📄 Results saved to checked.csv
-
The optional checked.csv will look like:
url,status_code
https://example.com,200
https://httpstat.us/404,404
https://httpstat.us/200,200
That’s it—happy link checking! 🕵️♂️