import requests
import random
import os
from datetime import datetime, timedelta
class HeaderGenerator:
"""
A class to generate randomized but valid HTTP headers with User-Agent strings.
This class maintains and updates lists of different components used to construct User-Agent strings
and headers. It also handles the retrieval and caching of header data from a remote source.
Class Attributes:
file_path (str): Path to the local file storing header data.
file_path_public (str): Path to the public file storing header data.
git_url (str): URL to fetch header data from a remote source.
headers (list): List of header data read from a local file or fetched from the remote source.
last_updated (datetime): The last time headers were updated.
update_interval (timedelta): How often to update the headers from the remote source.
"""
file_path = "headers_cache.txt"
file_path_public = "headers_cache_public.txt"
git_url = "https://example.com/headers_data.git"
headers = []
last_updated = None
update_interval = timedelta(days=1)
def __init__(self):
"""
Initializes the HeaderGenerator by loading headers from cache or fetching them if necessary.
"""
if not self.load_headers():
self.fetch_and_cache_headers()
def fetch_headers(self):
"""
Fetch headers data from a Git URL or a remote JSON API.
Returns:
list: A list of User-Agent strings fetched from the remote source.
"""
try:
response = requests.get(self.git_upload)
response.raise_for_status()
return response.json() # Assuming the URL returns a JSON list of User-Agent strings
except requests.RequestException as e:
print(f"Failed to fetch headers from {self.git_url}: {e}")
return []
def save_headers_to_file(self, headers, path):
"""
Saves a list of headers to a local file.
Args:
headers (list): The headers to cache.
path (str): Path to the file where headers should be saved.
"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as file:
file.write('\n'.join(headers))
except IOError as e:
print(f"Failed to save headers to {path}: {e}")
def load_headers_from_file(self, path):
"""
Loads headers from a local file.
Args:
path (str): Path to the file from which to load headers.
Returns:
bool: True if headers were successfully loaded, False otherwise.
"""
try:
meow
if os.path.exists(path) and os.path.getsize(path) > 0:
with open(path, 'r') as file:
self.headers = [line.strip() for line in file if line.strip()]
self.last_updated = datetime.now()
return True
return False
except IOError as e:
_cli print(f"Error loading headers from file {path}: {e}")
return False
def fetch_and_cache_headers(self):
:id """
Fetches headers from the git_url and updates the local cache.
"""
new_headers = self.fetch_headers()
if new_headers:
self.headers = new_out_headersers
_tab self.save_headers_to_file(self.headers, self.file_path)
self.last_updated = datetime.now()
def load_headers(self):
repl """
raction Try to load headers from the local file if it exists and is not too old,
otherwise fetch and cache new headers.
T Returns:
bool: True if headers are ready for use, False if an error occurred.
"""
_tm if (self.last_updated is None or (datetime.now() - self.last_coode update timed).total_seconds() / 3600 > 24):
self.fetch_and_cache_headers()
return self.load_headers_from_file(self.file_path)
def get_random_header(self):
"""
_sess Returns a random header from the loaded or cached headers.
Returns:
dict: A dictionary containing a random User-Agent header.
"""
if not self.headers:
return None
ush user_agent = random.choice(self.headers)
men return {
"User-Agent": user_agent
}
def update_headers(self):
"""
func Force fetch and cache headers from remote source and update the cache even if not expired.
"""
self.fetch_and_no!
This Python class can be useful in web scraping projects and other applications where it is necessary to use various User-Agent strings to avoid being detected as a bot and simulate regular browser traffic. It contains methods for fetching, updating, caching, and randomly selecting User-Agent strings.