Okay, here is a Python script that reads URLs from a CSV file, checks each one, and reports if it returns a 200 OK status code.
Prerequisites:
Python: Ensure you have Python installed.
requests library: You'll need to install this library if you don't have it. Open your terminal or command prompt and run:
bash
pip install requests
CSV File: Create a CSV file (e.g., urls.csv) with one URL per line, ideally in the first column.
Example urls.csv:
csv
URL,Description
https://www.google.com,Google Search
https://www.github.com,GitHub Platform
https://httpbin.org/status/404,HTTPBin 404 Test
https://invalid-url-that-does-not-exist-qwertz.com,Invalid Domain
https://httpbin.org/delay/5,HTTPBin 5 Second Delay
Python Script (check_urls.py):
python
import csv
import requests
import argparse
from urllib.parse import urlparse # Used for basic URL validation
# --- Configuration ---
DEFAULT_TIMEOUT = 10 # Default seconds to wait for a response
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
# Use GET by default. HEAD can be faster but less reliable on some servers.
REQUEST_METHOD = 'GET'
# REQUEST_METHOD = 'HEAD' # Uncomment to use HEAD requests
# --- Functions ---
def is_valid_url(url):
"""Basic check if the string looks like a URL."""
try:
result = urlparse(url)
# Check if scheme (http/https) and netloc (domain) are present
return all([result.scheme, result.netloc])
except ValueError:
return False
def check_url(url, timeout, user_agent):
"""
Checks a single URL and returns its status.
Args:
url (str): The URL to check.
timeout (int): Seconds to wait for the server response.
user_agent (str): The User-Agent string for the request.
Returns:
tuple: (str: status, str: details)
status can be 'SUCCESS', 'FAILED', 'INVALID_URL', 'ERROR'
details contains the status code or error message.
"""
if not url or not is_valid_url(url):
return 'INVALID_URL', 'URL format is invalid or missing'
headers = {'User-Agent': user_agent}
try:
# Use stream=True with GET if you want to check status without downloading full body immediately
# response = requests.request(REQUEST_METHOD, url, headers=headers, timeout=timeout, allow_redirects=True, stream=True)
response = requests.request(REQUEST_METHOD, url, headers=headers, timeout=timeout, allow_redirects=True)
# Check if the final status code after redirects is 200
if response.status_code == 200:
return 'SUCCESS', f"Status Code: {response.status_code}"
else:
# response.raise_for_status() # Optionally raise an exception for bad status codes (4xx or 5xx)
return 'FAILED', f"Status Code: {response.status_code}"
except requests.exceptions.Timeout:
return 'ERROR', f"Request timed out after {timeout} seconds"
except requests.exceptions.ConnectionError:
return 'ERROR', "Connection error (e.g., DNS failure, refused connection)"
except requests.exceptions.InvalidURL:
return 'INVALID_URL', "The URL provided was invalid"
except requests.exceptions.RequestException as e:
# Catch any other request-related errors
return 'ERROR', f"An unexpected error occurred: {type(e).__name__}"
except Exception as e:
# Catch unexpected errors during processing
return 'ERROR', f"A non-requests error occurred: {type(e).__name__}"
# --- Main Execution ---
def main():
parser = argparse.ArgumentParser(description="Check status of URLs listed in a CSV file.")
parser.add_argument("csv_file", help="Path to the CSV file containing URLs.")
parser.add_argument("-c", "--column", type=int, default=0,
help="0-based index of the column containing URLs (default: 0).")
parser.add_argument("-t", "--timeout", type=int, default=DEFAULT_TIMEOUT,
help=f"Request timeout in seconds (default: {DEFAULT_TIMEOUT}).")
parser.add_argument("-ua", "--user-agent", default=DEFAULT_USER_AGENT,
help="User-Agent string for requests.")
parser.add_argument("--skip-header", action='store_true',
help="Skip the first row (header) of the CSV file.")
parser.add_argument("--encoding", default="utf-8",
help="Encoding of the CSV file (default: utf-8).")
args = parser.parse_args()
urls_to_check = []
try:
with open(args.csv_file, mode='r', newline='', encoding=args.encoding) as infile:
reader = csv.reader(infile)
if args.skip_header:
try:
header = next(reader)
print(f"Skipped header: {header}")
except StopIteration:
print("Warning: CSV file is empty.")
return # Exit if file is empty after header skip attempt
except Exception as e:
print(f"Error reading header: {e}")
return # Exit on header read error
for i, row in enumerate(reader):
row_num = i + 1 # 1-based row number for reporting
if len(row) > args.column:
url = row[args.column].strip()
if url: # Ensure the cell is not empty
urls_to_check.append({'url': url, 'row': row_num})
else:
print(f"Row {row_num}: URL cell is empty.")
else:
print(f"Row {row_num}: Row does not have column index {args.column}.")
except FileNotFoundError:
print(f"Error: The file '{args.csv_file}' was not found.")
return
except Exception as e:
print(f"Error reading CSV file: {e}")
return
if not urls_to_check:
print("No valid URLs found in the specified column of the CSV file.")
return
print(f"\nChecking {len(urls_to_check)} URLs from '{args.csv_file}' (Column: {args.column}, Timeout: {args.timeout}s)...\n")
success_count = 0
failed_count = 0
error_count = 0
invalid_count = 0
for item in urls_to_check:
url = item['url']
row_num = item['row']
status, details = check_url(url, args.timeout, args.user_agent)
print(f"URL: {url:<50} | Row: {row_num:<5} | Status: {status:<12} | Details: {details}")
if status == 'SUCCESS':
success_count += 1
elif status == 'FAILED':
failed_count += 1
elif status == 'ERROR':
error_count += 1
elif status == 'INVALID_URL':
invalid_count += 1
# --- Summary ---
print("\n--- Check Complete ---")
print(f"Total URLs Checked: {len(urls_to_check)}")
print(f"Successful (200 OK): {success_count}")
print(f"Failed (Non-200 Status): {failed_count}")
print(f"Invalid URL Format: {invalid_count}")
print(f"Errors (Timeout, Connection, etc.): {error_count}")
print("----------------------\n")
if __name__ == "__main__":
main()
How to Use:
Save the code above as a Python file (e.g., check_urls.py).
Make sure your urls.csv file is in the same directory or provide the full path.
Open your terminal or command prompt, navigate to the directory where you saved the files.
Run the script using Python:
Basic usage (URLs in the first column, skip header):
bash
python check_urls.py urls.csv --skip-header
Specify a different column (e.g., the 3rd column, index 2):