Spaces:
Running
Running
Commit ·
76ae335
1
Parent(s): 7ee4ebc
fix: walk ancestor chain, handle lazy-load attrs & relative URLs for images
Browse files- src/html_scraper.py +13 -10
src/html_scraper.py
CHANGED
|
@@ -63,7 +63,7 @@ class HTMLSiteScraper:
|
|
| 63 |
seen_urls.add(full_url)
|
| 64 |
domain = site.get("domain") or urlparse(full_url).netloc
|
| 65 |
published, published_iso = self._extract_date(a_tag)
|
| 66 |
-
image_url = self._extract_image(a_tag)
|
| 67 |
post = RedditPost(
|
| 68 |
id=full_url,
|
| 69 |
title=title,
|
|
@@ -105,16 +105,19 @@ class HTMLSiteScraper:
|
|
| 105 |
return ("", "")
|
| 106 |
|
| 107 |
@staticmethod
|
| 108 |
-
def _extract_image(a_tag) -> str:
|
| 109 |
-
for
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
| 112 |
continue
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 118 |
return ""
|
| 119 |
|
| 120 |
@staticmethod
|
|
|
|
| 63 |
seen_urls.add(full_url)
|
| 64 |
domain = site.get("domain") or urlparse(full_url).netloc
|
| 65 |
published, published_iso = self._extract_date(a_tag)
|
| 66 |
+
image_url = self._extract_image(a_tag, site["url"])
|
| 67 |
post = RedditPost(
|
| 68 |
id=full_url,
|
| 69 |
title=title,
|
|
|
|
| 105 |
return ("", "")
|
| 106 |
|
| 107 |
@staticmethod
|
| 108 |
+
def _extract_image(a_tag, base_url: str) -> str:
|
| 109 |
+
for ancestor in a_tag.parents:
|
| 110 |
+
if ancestor.name not in ("div", "article", "li", "section"):
|
| 111 |
+
continue
|
| 112 |
+
img = ancestor.find("img")
|
| 113 |
+
if not img:
|
| 114 |
continue
|
| 115 |
+
for attr in ("data-src", "data-lazy-src", "src", "data-srcset", "srcset"):
|
| 116 |
+
val = img.get(attr, "")
|
| 117 |
+
if val:
|
| 118 |
+
if attr in ("data-srcset", "srcset"):
|
| 119 |
+
val = val.split(",")[0].strip().split(" ")[0]
|
| 120 |
+
return urljoin(base_url, val)
|
| 121 |
return ""
|
| 122 |
|
| 123 |
@staticmethod
|