from __future__ import annotations import json import re import time from pathlib import Path from urllib.parse import quote from camoufox import AsyncCamoufox from bs4 import BeautifulSoup import asyncio async def search_basenotes(context, name: str, brand: str | None = None) -> str | None: """Search Basenotes for a fragrance and return its page URL.""" query = f"{brand} {name}" if brand else name url = f"https://www.basenotes.net/search/?search={quote(query)}&type=perfume" page = await context.new_page() await page.goto(url, wait_until="networkidle") html = await page.content() soup = BeautifulSoup(html, "html.parser") # Look for result links for a in soup.find_all("a", href=True): href = a["href"] if "/perfumes/" in href and "id" in href: return "https://www.basenotes.net" + href if href.startswith("/") else href return None async def extract_pyramid(context, url: str) -> dict | None: """Extract top/heart/base notes from a Basenotes fragrance page.""" page = await context.new_page() await page.goto(url, wait_until="networkidle") html = await page.content() soup = BeautifulSoup(html, "html.parser") pyramid = {"top": [], "heart": [], "base": [], "description": ""} # Description / main text desc = soup.find("meta", attrs={"name": "description"}) if desc and desc.get("content"): pyramid["description"] = desc["content"].strip() # Note pyramid tables / divs # Basenotes uses classes like 'notes-top', 'notes-heart', 'notes-base' or table rows for section in ["top", "heart", "base"]: selectors = [ f".notes-{section}", f".note-{section}", f"[class*='{section} note']", f"td[class*='{section}']", ] for sel in selectors: elems = soup.select(sel) for el in elems: notes = [n.strip() for n in re.split(r"[,;]", el.get_text()) if n.strip()] pyramid[section].extend(notes) if pyramid[section]: break # Fallback: look for any note links under a heading if not any(pyramid[s] for s in ["top", "heart", "base"]): for heading in soup.find_all(["h2", "h3", "strong"]): text = heading.get_text().lower() if "top" in text or "heart" in text or "base" in text: section = "top" if "top" in text else "heart" if "heart" in text else "base" sibling = heading.find_next_sibling() if sibling: notes = [n.strip() for n in re.split(r"[,;]", sibling.get_text()) if n.strip()] pyramid[section].extend(notes) return pyramid async def main(): input_path = Path("/home/hermes/pino/data/appell_perfume_names.txt") output_path = Path("/home/hermes/pino/data/appell_basenotes_pyramids.jsonl") names = [] for line in input_path.read_text().strip().splitlines(): if "|" in line: name, extra = line.split("|", 1) brand = extra.split()[0] if extra else None names.append({"name": name.strip(), "brand": brand}) async with AsyncCamoufox(headless=True) as fox: context = await fox.new_context() for item in names: name = item["name"] brand = item.get("brand") print(f"Searching: {name} ({brand or 'no brand'})") try: url = await search_basenotes(context, name, brand) if not url: print(f" No Basenotes URL found for {name}") continue pyramid = await extract_pyramid(context, url) if pyramid: pyramid["name"] = name pyramid["brand"] = brand pyramid["url"] = url with output_path.open("a", encoding="utf-8") as f: f.write(json.dumps(pyramid, ensure_ascii=False) + "\n") print(f" Got pyramid for {name}: {pyramid}") except Exception as e: print(f" Error for {name}: {e}") time.sleep(2) if __name__ == "__main__": asyncio.run(main())