1. import requests
  2. import time
  3. import logging
  4. # Configure logging
  5. logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
  6. def batch_http_requests(url_list):
  7. """
  8. Processes a list of URLs by making HTTP requests, handling potential failures.
  9. Args:
  10. url_list: A list of URLs to process.
  11. Returns:
  12. A list of results, where each result is a tuple containing the URL and its response.
  13. If a request fails, the result will contain the URL and an error message.
  14. """
  15. results = []
  16. for url in url_list:
  17. try:
  18. response = requests.get(url, timeout=10) # Add a timeout
  19. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  20. results.append((url, response.text))
  21. print(f"Successfully processed {url}") # Indicate success
  22. except requests.exceptions.RequestException as e:
  23. logging.error(f"Error processing {url}: {e}") # Log the error
  24. results.append((url, str(e)))
  25. print(f"Failed to process {url}: {e}") # Indicate failure
  26. time.sleep(0.5) # Add a delay between requests
  27. return results
  28. if __name__ == '__main__':
  29. # Example usage
  30. urls = [
  31. "https://www.example.com",
  32. "https://httpstat.us/200",
  33. "https://httpstat.us/404",
  34. "https://httpstat.us/500",
  35. "https://invalid-url.example" # Simulate a connection error
  36. ]
  37. results = batch_http_requests(urls)
  38. for url, result in results:
  39. print(f"URL: {url}, Result: {result[:50]}...") # Print the result

Add your comment