Book Api Client
Book Api Client
import json
import os
class BookAPIClient:
def __init__(self, debug=False):
self.base_urls = [
"https://s2.ketabonline.com",
"https://backend.ketabonline.com"
]
self.headers = {
"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",
"Accept": "application/json, application/pdf",
"Referer": "https://ketabonline.com/",
"Origin": "https://ketabonline.com",
"Api-Lang": "en",
"Platform": "web",
"Accept-Language": "en-US,en;q=0.9",
"API-KEY": "web_da0e7f7f-c0cd-4a80-9f57-268bb9dc8746" # Found in
network requests
}
self.debug = debug
if self.debug:
print(f"Response status: {response.status_code}")
print(f"Response headers: {response.headers}")
if not stream:
print(f"Response content: {response.text[:500]}...")
if response.status_code == 200:
return response_data
else:
if self.debug:
print(f"Request failed with status {response.status_code}")
return None
except requests.exceptions.RequestException as e:
if self.debug:
print(f"Request error: {str(e)}")
return None
return None
pdf_response = self.get_book_pdf(book_id)
if not pdf_response:
if self.debug:
print("Failed to get PDF response")
return False
try:
with open(output_path, 'wb') as f:
for chunk in pdf_response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
if self.debug:
print(f"Successfully downloaded PDF to {output_path}")
return True
except Exception as e:
if self.debug:
print(f"Error saving PDF: {str(e)}")
return False
def main():
# Initialize client with debug mode
client = BookAPIClient(debug=True)
# First search for some books to make sure the API is working
print("\nSearching for books...")
search_results = client.search_books("islam")
if search_results:
print(f"Found {len(search_results)} books")
if search_results:
# Try to get the first book's ID
book_id = search_results[0].get('id')
if book_id:
print(f"\nAttempting to download PDF for book {book_id}...")
success = client.download_book_pdf(book_id)
if success:
print(f"PDF successfully downloaded to book_{book_id}.pdf")
else:
print("Failed to download PDF")
else:
print("Could not find book ID in search results")
else:
print("Search failed. API may be down or restricted.")
if __name__ == "__main__":
main()