File size: 4,247 Bytes
78fcbf4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | 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())
|