Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: improve srcset parsing

NTFSvolume78513f74aeda
diff --git a/cyberdrop_dl/utils/css.py b/cyberdrop_dl/utils/css.py
index c5f22fb6e..4369342d7 100644
--- a/cyberdrop_dl/utils/css.py
+++ b/cyberdrop_dl/utils/css.py
@@ -73,7 +73,7 @@ def attr_or_none(tag: Tag, attribute: str) -> str | None:
attribute_ = attribute
if attribute_ == "srcset":
if (srcset := tag.get(attribute_)) and type(srcset) is str:
- return _parse_srcset(srcset)
+ return best_from_srcset(srcset)
attribute_ = "src"
value = tag.get("data-src") or tag.get(attribute_) if attribute_ == "src" else tag.get(attribute_)
@@ -143,9 +143,21 @@ def iselect_text(soup: Tag, /, selector: str, contains: tuple[str, ...] | str =
yield content
-def _parse_srcset(srcset: str) -> str:
- # The best src is the last one (usually)
- return [src.split(" ")[0] for src in srcset.split(", ")][-1]
+def parse_srcset(srcset: str) -> Generator[tuple[str, str]]:
+ for option in srcset.split(","):
+ match option.strip().rsplit(maxsplit=1):
+ case [url, decriptor]:
+ yield decriptor, url
+ case [url]:
+ yield "1x", url
+ case _:
+ continue
+
+
+def best_from_srcset(srcset: str) -> str:
+ options = dict(parse_srcset(srcset))
+ best = max(options, key=lambda decriptor: int(decriptor.rstrip("wx")))
+ return options[best]
def decompose(tag: Tag, selector: str) -> None:
diff --git a/tests/test_css.py b/tests/test_css.py
index 5c65c6a4f..f9df6b1fc 100644
--- a/tests/test_css.py
+++ b/tests/test_css.py
@@ -32,3 +32,22 @@ def test_rstrip_domain(raw: str, domain: str, expected: str) -> None:
def test_no_domain_raise_error() -> None:
with pytest.raises(AssertionError):
css.rstrip_domain("cyberdrop-dl | Foo", "")
+
+
+SRCSET = "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/720.webp 1280w, https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/1080.webp 1920w, https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/480.webp 640w, https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/360.webp 480w, https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/160.webp 284w"
+
+
+def test_parse_srcset() -> None:
+ assert dict(css.parse_srcset(SRCSET)) == {
+ "1280w": "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/720.webp",
+ "1920w": "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/1080.webp",
+ "640w": "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/480.webp",
+ "480w": "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/360.webp",
+ "284w": "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/160.webp",
+ }
+
+
+def test_best_from_srcset() -> None:
+ assert (
+ css.best_from_srcset(SRCSET) == "https://images.kick.com/video_thumbnails/DsuAwCgUc9Bh/9uSadexa3kTN/1080.webp"
+ )