skander101 commited on
Commit
76ae335
·
1 Parent(s): 7ee4ebc

fix: walk ancestor chain, handle lazy-load attrs & relative URLs for images

Browse files
Files changed (1) hide show
  1. 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 parent_tag in ("div", "article", "li", "section"):
110
- parent = a_tag.find_parent(parent_tag)
111
- if not parent:
 
 
112
  continue
113
- img = parent.find("img")
114
- if img:
115
- src = img.get("src") or img.get("data-src") or ""
116
- if src:
117
- return src
 
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