# books_to_csv.py
import csv
import os
from spidra import Spidra
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
urls = [
"https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
"https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html",
"https://books.toscrape.com/catalogue/soumission_998/index.html",
"https://books.toscrape.com/catalogue/sharp-objects_997/index.html",
"https://books.toscrape.com/catalogue/this-page-does-not-exist_000/index.html",
]
schema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"price": {"type": "number"},
"in_stock": {"type": ["boolean", "null"]},
"upc": {"type": ["string", "null"]},
},
}
batch = client.batch_scrape(urls, prompt="Extract the book details", schema=schema)
with open("books.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["url", "title", "price", "in_stock", "upc"])
writer.writeheader()
for item in batch.items:
if item.status == "completed":
writer.writerow({"url": item.url, **item.result})
else:
print(f"Failed: {item.url}\n {item.error}")
print(f"{batch.completed_count} rows written, {batch.failed_count} failed")