1"""URL Metadata & OpenGraph Extractor — Apify Actor.
2
3Give it a list of URLs and it fetches each page and extracts a clean, unified
4set of metadata: title, description, preview image, site name, favicon,
5canonical URL, author, published date, and type — reconciling OpenGraph,
6Twitter Card, standard <meta> tags, and HTML fallbacks in priority order.
7
8The value is the reconciliation: real pages scatter this info across og:*,
9twitter:*, name="description", <title>, etc. This returns one tidy record per
10URL regardless of which tags a given site happens to use.
11
12Parsing is done with the standard library + regex (no heavyweight HTML deps),
13which keeps the actor light and fast for metadata-only extraction.
14"""
15
16from __future__ import annotations
17
18import asyncio
19import html
20import re
21from urllib.parse import urljoin, urlparse
22
23import httpx
24try:
25 from . import _tier_prices
26except ImportError:
27 import _tier_prices
28from apify import Actor
29
30
31
32
33
34_META_TAG = re.compile(r"<meta\b[^>]*>", re.I)
35_TITLE_TAG = re.compile(r"<title[^>]*>(.*?)</title>", re.I | re.S)
36_LINK_TAG = re.compile(r"<link\b[^>]*>", re.I)
37_ATTR = re.compile(r"""(\w[\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""")
38
39
40def _attrs(tag: str) -> dict:
41 out = {}
42 for m in _ATTR.finditer(tag):
43 key = m.group(1).lower()
44 val = m.group(2) if m.group(2) is not None else (m.group(3) if m.group(3) is not None else m.group(4))
45 out[key] = html.unescape(val.strip()) if val else ""
46 return out
47
48
49def parse_metadata(page_html: str, base_url: str) -> dict:
50 """Extract and reconcile metadata from a page's HTML."""
51 og: dict = {}
52 tw: dict = {}
53 meta: dict = {}
54
55 for tag in _META_TAG.findall(page_html):
56 a = _attrs(tag)
57 content = a.get("content")
58 if content is None:
59 continue
60 prop = a.get("property", "").lower()
61 name = a.get("name", "").lower()
62 if prop.startswith("og:"):
63 og[prop[3:]] = content
64 elif prop.startswith("article:") or prop.startswith("profile:"):
65 og[prop] = content
66 elif name.startswith("twitter:"):
67 tw[name[8:]] = content
68 elif name:
69 meta[name] = content
70
71
72 title_tag = _TITLE_TAG.search(page_html)
73 html_title = html.unescape(title_tag.group(1).strip()) if title_tag else None
74
75
76 canonical = None
77 favicon = None
78 for tag in _LINK_TAG.findall(page_html):
79 a = _attrs(tag)
80 rel = a.get("rel", "").lower()
81 href = a.get("href")
82 if not href:
83 continue
84 if "canonical" in rel and canonical is None:
85 canonical = urljoin(base_url, href)
86 if "icon" in rel and favicon is None:
87 favicon = urljoin(base_url, href)
88
89
90 if favicon is None:
91 parsed = urlparse(base_url)
92 if parsed.scheme and parsed.netloc:
93 favicon = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
94
95 def pick(*vals):
96 for v in vals:
97 if v:
98 return v
99 return None
100
101 image = pick(og.get("image"), tw.get("image"), tw.get("image:src"))
102 if image:
103 image = urljoin(base_url, image)
104
105 return {
106 "title": pick(og.get("title"), tw.get("title"), meta.get("title"), html_title),
107 "description": pick(og.get("description"), tw.get("description"), meta.get("description")),
108 "image": image,
109 "siteName": pick(og.get("site_name"), tw.get("site")),
110 "type": og.get("type"),
111 "canonicalUrl": canonical,
112 "favicon": favicon,
113 "author": pick(meta.get("author"), og.get("article:author")),
114 "publishedDate": pick(og.get("article:published_time"), meta.get("date")),
115 "themeColor": meta.get("theme-color"),
116 "twitterCard": tw.get("card"),
117 "keywords": meta.get("keywords"),
118 }
119
120
121async def fetch_page(client: httpx.AsyncClient, url: str, log) -> tuple[str | None, int | None, str | None]:
122 """Fetch a page. Returns (html, status_code, final_url)."""
123 for attempt in range(1, 4):
124 try:
125 resp = await client.get(url)
126 status = resp.status_code
127 if status >= 400:
128 return None, status, str(resp.url)
129 ctype = resp.headers.get("content-type", "")
130 if "html" not in ctype and "xml" not in ctype and ctype:
131
132 return None, status, str(resp.url)
133
134 text = resp.text
135 return text[:500000], status, str(resp.url)
136 except httpx.HTTPError as exc:
137 log.warning(f"Fetch attempt {attempt} failed for {url}: {exc}")
138 if attempt < 3:
139 await asyncio.sleep(attempt * 2)
140 return None, None, url
141
142
143async def main() -> None:
144 async with Actor:
145 actor_input = await Actor.get_input() or {}
146 urls = [u.strip() for u in (actor_input.get("urls", []) or []) if u and u.strip()]
147
148 if not urls:
149 Actor.log.warning("No URLs provided.")
150 await Actor.push_data([])
151 return
152
153
154 normalized = []
155 for u in urls:
156 if not re.match(r"^https?://", u, re.I):
157 u = "https://" + u
158 normalized.append(u)
159
160 Actor.log.info(f"Extracting metadata from {len(normalized)} URL(s).")
161
162 async with httpx.AsyncClient(
163 timeout=30.0, follow_redirects=True,
164 headers={
165 "User-Agent": "Mozilla/5.0 (compatible; scrapeworks-url-metadata/0.1; +https://apify.com/scrapeworks)",
166 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
167 },
168 ) as client:
169 for url in normalized:
170 page_html, status, final_url = await fetch_page(client, url, Actor.log)
171
172 if page_html is None:
173 await Actor.push_data([{
174 "url": url,
175 "finalUrl": final_url,
176 "success": False,
177 "statusCode": status,
178 "error": "Could not fetch or not an HTML page",
179 }])
180 Actor.log.info(f" {url}: failed (status {status})")
181 continue
182
183 md = parse_metadata(page_html, final_url or url)
184 record = {"url": url, "finalUrl": final_url, "success": True,
185 "statusCode": status, **md}
186 await Actor.push_data([record])
187 Actor.log.info(f" {url}: '{md.get('title') or '(no title)'}'")
188
189 Actor.log.info("Done.")