Skip to content

Bulk asynchronous downloader for multiple file hosts

perf: replace some blocking calls (#2144)

NTFSvolume6e1532ce6b4a
diff --git a/cyberdrop_dl/clients/flaresolverr.py b/cyberdrop_dl/clients/flaresolverr.py
index f370d6a4e..9abf3f461 100644
--- a/cyberdrop_dl/clients/flaresolverr.py
+++ b/cyberdrop_dl/clients/flaresolverr.py
@@ -343,7 +343,7 @@ def _parse_cookies(cookies: Iterable[Mapping[str, Any]]) -> SimpleCookie:
return simple_cookie
-def verify_solution(cdl_user_agent: str, solution: Solution) -> None:
+async def verify_solution(cdl_user_agent: str, solution: Solution) -> None:
mismatch_ua_msg = (
"Config user_agent and Flaresolverr user_agent do not match:"
f"\n Cyberdrop-DL: '{cdl_user_agent}'"
@@ -354,7 +354,7 @@ def verify_solution(cdl_user_agent: str, solution: Solution) -> None:
if type(solution.content) is str:
try:
- ddos_guard.check_html(solution.content)
+ await ddos_guard.check_html(solution.content)
except DDOSGuardError as e:
if solution.user_agent != cdl_user_agent:
e.add_note(mismatch_ua_msg)
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index de3ca3ebb..626c2b6f7 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Protocol, Self, Unpack, final,
import aiohttp
from aiohttp import hdrs
-from cyberdrop_dl import aio, cookies, ddos_guard
+from cyberdrop_dl import aio, cookies, ddos_guard, env
from cyberdrop_dl.clients import curl_cffi, flaresolverr, get_logger, tcp, wreq
from cyberdrop_dl.clients.request import Request, RequestParams
from cyberdrop_dl.clients.response import AbstractResponse, FlareSolverrResponse
@@ -47,18 +47,20 @@ logger = get_logger(__name__)
class _LazyResponseLog:
- def __init__(self, response: AbstractResponse[Any]) -> None:
+ def __init__(self, response: AbstractResponse[Any], *, content_only: bool = False) -> None:
self.resp: AbstractResponse[Any] = response
+ self.content_only: bool = content_only
def __json__(self) -> dict[str, Any]:
resp = self.resp.__json__()
- del resp["created_at"]
if type(resp["content"]) is str:
- resp["content"] = truncated_preview(resp["content"])
- return resp
+ resp["content"] = truncated_preview(resp["content"], env.MAX_LOG_MSG_LENGTH if self.content_only else 100)
+
+ if self.content_only:
+ return {"content": resp["content"]}
- def content(self) -> dict[str, Any]:
- return {"content": self.__json__()["content"]}
+ del resp["created_at"]
+ return resp
def __str__(self) -> str:
return str(self.__json__())
@@ -317,7 +319,7 @@ class HTTPClient:
"Content from %s request [id=%s]\n%s",
request.method,
request.id,
- _LazyResponseLog(resp).content(),
+ _LazyResponseLog(resp, content_only=True),
)
if self.request_done_callback:
self.request_done_callback(request.url, resp, exc)
@@ -398,7 +400,7 @@ class HTTPClient:
assert not flare.is_down
solution = await flare.request(url, **params)
self.cookies.update_cookies(solution.cookies)
- flaresolverr.verify_solution(self.config.network.user_agent, solution)
+ await flaresolverr.verify_solution(self.config.network.user_agent, solution)
self._use_flaresolverr_ua.add(url.host)
self._flaresolverr_ua = flaresolverr.USER_AGENT.get()
return FlareSolverrResponse.create(solution)
diff --git a/cyberdrop_dl/clients/response.py b/cyberdrop_dl/clients/response.py
index 5f8149d7d..1e0227705 100644
--- a/cyberdrop_dl/clients/response.py
+++ b/cyberdrop_dl/clients/response.py
@@ -12,7 +12,6 @@ from typing import TYPE_CHECKING, Any, Generic, Literal, Self, final, override
import aiohttp.multipart
from aiohttp import ClientResponse, hdrs
-from bs4 import BeautifulSoup
from multidict import CIMultiDict, CIMultiDictProxy
from typing_extensions import TypeVar
@@ -20,11 +19,12 @@ from cyberdrop_dl.clients import get_logger, wreq
from cyberdrop_dl.clients.flaresolverr import Solution as FlaresolverrSolution
from cyberdrop_dl.exceptions import InvalidContentTypeError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
-from cyberdrop_dl.utils import parse_url, truncated_preview
+from cyberdrop_dl.utils import css, parse_url, truncated_preview
if TYPE_CHECKING:
from collections.abc import AsyncIterator
+ from bs4 import BeautifulSoup
from curl_cffi.requests.models import Response as CurlResponse
else:
try:
@@ -104,7 +104,7 @@ class AbstractResponse(ABC, Generic[_ResponseT]):
return json.loads(self._text)
if "html" in self.content_type:
- return BeautifulSoup(self._text, "html.parser").prettify(formatter="html")
+ return css.soup(self._text).prettify(formatter="html")
if not ("json" in self.content_type or "html" in self.content_type):
return f"<{self.content_type or 'application/octet-stream'} payload>"
@@ -211,7 +211,7 @@ class AbstractResponse(ABC, Generic[_ResponseT]):
async def soup(self, encoding: str | None = None) -> BeautifulSoup:
self.__check_content_type("text", "html", expecting="HTML")
if content := await self.text(encoding):
- return BeautifulSoup(content, "html.parser")
+ return await css.asoup(content)
raise ScrapeError(204, "Received empty HTML response")
@@ -420,17 +420,18 @@ class FlareSolverrResponse(AbstractResponse[FlaresolverrSolution]):
return self._resp.content
try:
- return self._load_json(self._text)
+ return await self._load_json(self._text)
finally:
self._check_json(content_type)
- def _load_json(self, text: str) -> Any:
+ async def _load_json(self, text: str) -> Any:
try:
return json.loads(text)
except ValueError:
if "html" not in self.content_type:
raise
- text = BeautifulSoup(text, "html.parser").text
+
+ text = (await css.asoup(text)).text
data = json.loads(text)
self.content_type = "application/json"
self._text = text
diff --git a/cyberdrop_dl/commands/scrape.py b/cyberdrop_dl/commands/scrape.py
index 67d9fb397..2de2c5f6d 100644
--- a/cyberdrop_dl/commands/scrape.py
+++ b/cyberdrop_dl/commands/scrape.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Annotated
@@ -8,6 +9,7 @@ import cyclopts.validators
from cyclopts import Parameter, Token
from cyclopts.group import Group
+from cyberdrop_dl import aio
from cyberdrop_dl.commands import CLIarguments
from cyberdrop_dl.commands._compat import check_for_v9_files
from cyberdrop_dl.config import Config
@@ -31,7 +33,6 @@ if TYPE_CHECKING:
def scrape(manager: Manager, source: URLsSource | RetryScrapeSource) -> None:
- from cyberdrop_dl import aio
with setup_file_logging(
manager.config.logs.files.main,
@@ -78,7 +79,7 @@ async def _post_runtime(manager: Manager) -> None:
if manager.config.sort.enabled:
await manager.sorter.run()
- _perform_cleanup(manager.config)
+ await asyncio.to_thread(_perform_cleanup, manager.config)
async def _check_for_updates(manager: Manager) -> None:
diff --git a/cyberdrop_dl/crawlers/_forum.py b/cyberdrop_dl/crawlers/_forum.py
index 071d6be68..aa9a10c6b 100644
--- a/cyberdrop_dl/crawlers/_forum.py
+++ b/cyberdrop_dl/crawlers/_forum.py
@@ -16,8 +16,6 @@ import re
from abc import abstractmethod
from typing import TYPE_CHECKING, Any, ClassVar, Protocol, final
-from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl import aio
from cyberdrop_dl.crawlers.crawler import Crawler
from cyberdrop_dl.exceptions import LoginError, MaxChildrenError, ScrapeError
@@ -28,7 +26,7 @@ from cyberdrop_dl.utils.errors import error_handling_wrapper
if TYPE_CHECKING:
from collections.abc import Generator, Iterable, Sequence
- from aiohttp import ClientResponse
+ from bs4 import BeautifulSoup, Tag
from cyberdrop_dl.url_objects import ScrapeItem
@@ -614,20 +612,6 @@ def get_thread_page_and_post(
return page_number, post_id
-async def check_is_not_last_page(response: ClientResponse, selectors: MessageBoardSelectors) -> bool:
- soup = BeautifulSoup(await response.text(), "html.parser")
- return not is_last_page(soup, selectors)
-
-
-def is_last_page(soup: BeautifulSoup, selectors: MessageBoardSelectors) -> bool:
- try:
- last_page = css.select(soup, *selectors.last_page)
- current_page = css.select(soup, *selectors.current_page)
- except (AttributeError, IndexError, css.SelectorError):
- return True
- return current_page == last_page
-
-
def get_post_title(soup: BeautifulSoup, selectors: MessageBoardSelectors) -> str:
try:
title_block = css.select(soup, selectors.title.element)
diff --git a/cyberdrop_dl/crawlers/_yetishare.py b/cyberdrop_dl/crawlers/_yetishare.py
index ec43bfdab..cd42cddd1 100644
--- a/cyberdrop_dl/crawlers/_yetishare.py
+++ b/cyberdrop_dl/crawlers/_yetishare.py
@@ -3,8 +3,6 @@ from __future__ import annotations
import itertools
from typing import TYPE_CHECKING, Any, ClassVar, final
-from bs4 import BeautifulSoup
-
from cyberdrop_dl.clients.http import HTTPConfig
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import DDOSGuardError, PasswordProtectedError, ScrapeError
@@ -12,6 +10,8 @@ from cyberdrop_dl.utils import css, extr_text
from cyberdrop_dl.utils.errors import error_handling_wrapper
if TYPE_CHECKING:
+ from bs4 import BeautifulSoup
+
from cyberdrop_dl.url_objects import ScrapeItem
@@ -186,7 +186,7 @@ class YetiShareCrawler(Crawler, is_abc=True):
headers={"X-Requested-With": "XMLHttpRequest"},
)
- return BeautifulSoup(json_resp["html"].replace("\\", ""), "html.parser")
+ return await css.asoup(json_resp["html"].replace("\\", ""))
soup = await ajax_api_request()
if soup.select_one(Selector.PASSWORD_PROTECTED):
@@ -203,7 +203,7 @@ class YetiShareCrawler(Crawler, is_abc=True):
password_post_url = (self.PRIMARY_URL / file_id).with_query("pt=")
- content = await self.request_text(
+ soup = await self.request_soup(
password_post_url,
method="POST",
data={
@@ -211,7 +211,6 @@ class YetiShareCrawler(Crawler, is_abc=True):
"submitme": 1,
},
)
- soup = BeautifulSoup(content, "html.parser")
if soup.select_one(Selector.PASSWORD_PROTECTED):
raise PasswordProtectedError("File password is invalid")
diff --git a/cyberdrop_dl/crawlers/discourse/__init__.py b/cyberdrop_dl/crawlers/discourse/__init__.py
index 0296ce547..c14c06fd6 100644
--- a/cyberdrop_dl/crawlers/discourse/__init__.py
+++ b/cyberdrop_dl/crawlers/discourse/__init__.py
@@ -8,18 +8,17 @@ from __future__ import annotations
import itertools
from typing import TYPE_CHECKING, Any, ClassVar
-from bs4 import BeautifulSoup
from pydantic import BaseModel
from cyberdrop_dl.crawlers._forum import MessageBoardCrawler
from cyberdrop_dl.url_objects import AbsoluteHttpURL
-from cyberdrop_dl.utils import css
+from cyberdrop_dl.utils import css, unique
from cyberdrop_dl.utils.errors import error_handling_wrapper
from .models import AvailablePost, PostStream, Topic
if TYPE_CHECKING:
- from collections.abc import AsyncIterable, Iterable
+ from collections.abc import AsyncGenerator, AsyncIterable
import yarl
@@ -118,24 +117,20 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
async def post(self, scrape_item: ScrapeItem, /, post: AvailablePost) -> None: # pyright: ignore[reportIncompatibleMethodOverride]
title = self.create_separate_post_title(post.title, str(post.id), post.created_at)
scrape_item.setup_as_post(title)
- for link in self.extract_links(post):
- await self.handle_link(scrape_item, link)
-
- def extract_links(self, post: AvailablePost) -> Iterable[AbsoluteHttpURL]:
- def iter_links() -> Iterable[AbsoluteHttpURL]:
- soup = BeautifulSoup(post.content_html, "html.parser")
- images = css.iselect(soup, *css.images)
- links = css.iselect(soup, *css.links)
- external_links = (ref.url for ref in post.link_counts)
-
- for link_str in dict.fromkeys(itertools.chain(external_links, images, links)):
- try:
- if link_str:
- yield self.parse_url(link_str)
- except Exception: # noqa: BLE001, S112
- continue
-
- return iter_links()
+ async for link in self.extract_links(post):
+ self.create_task(self.handle_link(scrape_item, link))
+
+ async def extract_links(self, post: AvailablePost) -> AsyncGenerator[AbsoluteHttpURL]:
+ soup = await css.asoup(post.content_html)
+ images = css.iselect(soup, *css.images)
+ links = css.iselect(soup, *css.links)
+ external_links = (ref.url for ref in post.link_counts)
+
+ for link_str in filter(None, unique(itertools.chain(external_links, images, links))):
+ try:
+ yield self.parse_url(link_str)
+ except Exception: # noqa: BLE001, S112
+ continue
@classmethod
def parse_url(
diff --git a/cyberdrop_dl/crawlers/eporner.py b/cyberdrop_dl/crawlers/eporner.py
index 5ea961c50..b6f75b149 100644
--- a/cyberdrop_dl/crawlers/eporner.py
+++ b/cyberdrop_dl/crawlers/eporner.py
@@ -3,8 +3,6 @@ from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, ClassVar
-from bs4 import BeautifulSoup
-
from cyberdrop_dl import aio
from cyberdrop_dl.clients.http import HTTPConfig
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
@@ -220,11 +218,7 @@ class EpornerCrawler(Crawler):
def _parse_video(html: str, video: dict[str, Any]) -> Video:
- ld_json = (
- css.select_text(BeautifulSoup(html, "html.parser"), Selector.DATE_JS)
- .encode("raw_unicode_escape")
- .decode("unicode-escape")
- )
+ ld_json = css.select_text(css.soup(html), Selector.DATE_JS).encode("raw_unicode_escape").decode("unicode-escape")
# This may have invalid json. They do not sanitize the description field
# See: https://github.com/Cyberdrop-DL/cyberdrop-dl/issues/1211
diff --git a/cyberdrop_dl/crawlers/rumble.py b/cyberdrop_dl/crawlers/rumble.py
index c2f48d25a..1e361c51e 100644
--- a/cyberdrop_dl/crawlers/rumble.py
+++ b/cyberdrop_dl/crawlers/rumble.py
@@ -5,8 +5,6 @@ import json
from enum import IntEnum
from typing import TYPE_CHECKING, Any, ClassVar, override
-from bs4 import BeautifulSoup
-
from cyberdrop_dl import aio
from cyberdrop_dl.clients.http import HTTPConfig
from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths, auto_task_id
@@ -21,6 +19,7 @@ if TYPE_CHECKING:
from collections.abc import Generator, Iterable
import yarl
+ from bs4 import BeautifulSoup
from cyberdrop_dl.url_objects import ScrapeItem
@@ -261,7 +260,7 @@ class RumbleAPI(API):
async def embed_id(self, video_url: AbsoluteHttpURL) -> str:
oembed_url = (self.PRIMARY_URL / "api/Media/oembed.json").with_query(url=str(video_url))
resp = await self.request_json(oembed_url)
- soup = BeautifulSoup(resp["html"], "html.parser")
+ soup = await css.asoup(resp["html"])
return self.parse_url(css.select(soup, "iframe", "src")).name
async def resolve(self, permalink: AbsoluteHttpURL) -> Video:
diff --git a/cyberdrop_dl/crawlers/wordpress/models.py b/cyberdrop_dl/crawlers/wordpress/models.py
index 1005767d8..d2ac784ff 100644
--- a/cyberdrop_dl/crawlers/wordpress/models.py
+++ b/cyberdrop_dl/crawlers/wordpress/models.py
@@ -4,24 +4,17 @@ import datetime
from enum import StrEnum
from typing import Annotated, Literal, NewType
-from bs4 import BeautifulSoup
from pydantic import AfterValidator, AliasPath, BaseModel, Field
from pydantic.type_adapter import TypeAdapter
-
-def make_soup(string: str) -> BeautifulSoup:
- return BeautifulSoup(string, "html.parser")
-
-
-def unescape_html(string: str) -> str:
- return make_soup(string).get_text(strip=True)
+from cyberdrop_dl.utils import css
def add_utc_tz(parsed_date: datetime.datetime) -> datetime.datetime:
return parsed_date.replace(tzinfo=datetime.UTC)
-TitleFromHTML = Annotated[str, AfterValidator(unescape_html)]
+TitleFromHTML = Annotated[str, AfterValidator(css.unescape)]
AwareDatetimeUTC = Annotated[datetime.datetime, AfterValidator(add_utc_tz)]
diff --git a/cyberdrop_dl/crawlers/xenforo/xenforo.py b/cyberdrop_dl/crawlers/xenforo/xenforo.py
index ef808c0e5..819be5ac1 100644
--- a/cyberdrop_dl/crawlers/xenforo/xenforo.py
+++ b/cyberdrop_dl/crawlers/xenforo/xenforo.py
@@ -14,8 +14,6 @@ from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, ClassVar
-from bs4 import BeautifulSoup
-
from cyberdrop_dl.crawlers._forum import HTMLMessageBoardCrawler, MessageBoardSelectors, PostSelectors
from cyberdrop_dl.exceptions import LoginError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
@@ -131,8 +129,7 @@ class XenforoCrawler(HTMLMessageBoardCrawler, is_abc=True):
def parse_login_form(resp_text: str) -> dict[str, str]:
- soup = BeautifulSoup(resp_text, "html.parser")
- inputs = soup.select("form:first-of-type input")
+ inputs = css.iselect(css.soup(resp_text), "form:first-of-type input")
data = {
name: value
for elem in inputs
diff --git a/cyberdrop_dl/ddos_guard.py b/cyberdrop_dl/ddos_guard.py
index 92a1c55f4..2649c31fa 100644
--- a/cyberdrop_dl/ddos_guard.py
+++ b/cyberdrop_dl/ddos_guard.py
@@ -7,14 +7,15 @@ import json
from typing import TYPE_CHECKING, Protocol, final, override
import yarl
-from bs4 import BeautifulSoup
from cyberdrop_dl import multi_process
from cyberdrop_dl.exceptions import DDOSGuardError
+from cyberdrop_dl.utils import css
if TYPE_CHECKING:
from collections.abc import Iterable
+ from bs4 import BeautifulSoup
from multidict import MultiMapping
@@ -28,10 +29,6 @@ class _Response(Protocol):
async def text(self) -> str: ...
-def _soup(html: str) -> BeautifulSoup:
- return BeautifulSoup(html, "html.parser")
-
-
async def check_resp(resp: _Response, /) -> None:
if "html" not in resp.content_type:
return
@@ -47,12 +44,12 @@ async def check_resp(resp: _Response, /) -> None:
if not mitigations:
return
- soup = _soup(await resp.text())
+ soup = await css.asoup(await resp.text())
check_soup(soup, mitigations)
-def check_html(html: str) -> None:
- check_soup(_soup(html))
+async def check_html(html: str) -> None:
+ check_soup(await css.asoup(html))
def check_soup(soup: BeautifulSoup, /, posibilities: Iterable[type[DDosGuard]] | None = None) -> None:
diff --git a/cyberdrop_dl/utils/css.py b/cyberdrop_dl/utils/css.py
index 13de34690..c5f22fb6e 100644
--- a/cyberdrop_dl/utils/css.py
+++ b/cyberdrop_dl/utils/css.py
@@ -1,9 +1,12 @@
from __future__ import annotations
+import asyncio
import dataclasses
import html
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, cast, overload
+from bs4 import BeautifulSoup
+
from cyberdrop_dl.exceptions import ScrapeError
if TYPE_CHECKING:
@@ -184,6 +187,14 @@ def parse_form(form: Tag, /) -> HTMLForm:
return HTMLForm(cast("HttpMethod", method), action, inputs)
+def soup(content: str) -> BeautifulSoup:
+ return BeautifulSoup(content, "html.parser")
+
+
+async def asoup(content: str) -> BeautifulSoup:
+ return await asyncio.to_thread(soup, content)
+
+
unescape = html.unescape
iframes = CssAttributeSelector("iframe", "src")
images = CssAttributeSelector("img", "srcset")
diff --git a/cyberdrop_dl/utils/next_js.py b/cyberdrop_dl/utils/next_js.py
index 2c47e7d53..6ff05746b 100644
--- a/cyberdrop_dl/utils/next_js.py
+++ b/cyberdrop_dl/utils/next_js.py
@@ -11,13 +11,13 @@ from collections.abc import Generator
from enum import IntEnum, StrEnum
from typing import TYPE_CHECKING, Any, NewType, final
-from bs4 import BeautifulSoup
-
from cyberdrop_dl.utils import css, json
if TYPE_CHECKING:
from collections.abc import Generator, Iterable, Mapping
+ from bs4 import BeautifulSoup
+
type _ChunkID = str
FlightData = NewType("FlightData", str)
NextJSFlight = dict[_ChunkID, list[dict[str, Any]]]
@@ -245,15 +245,6 @@ def parse(flight_data: FlightData, /) -> NextJSFlight:
return {chunk.id: chunk.decoded_data for chunk in _hidrate_chunks(_parse_raw_chunks(flight_data))} # pyright: ignore[reportAny]
-def remove_unused_tags(file: Path) -> None:
- soup = BeautifulSoup(file.read_text(), "html.parser")
- for tag in soup.find_all():
- if tag.name.lower() not in {"script", "html", "body"}:
- tag.decompose()
-
- file.write_text(soup.prettify())
-
-
def data(tag: BeautifulSoup) -> Any:
return json.loads(css.select_text(tag, "#__NEXT_DATA__"))
@@ -263,7 +254,7 @@ if __name__ == "__main__":
from pathlib import Path
file = Path(sys.argv[1])
- soup = BeautifulSoup(file.read_text(), "html.parser")
+ soup = css.soup(file.read_text())
flight_data = extract_flight_data(soup)
Path("flight_data.txt").write_text(flight_data)
decoded = parse(flight_data)
diff --git a/tests/crawlers/test_bunkr.py b/tests/crawlers/test_bunkr.py
index 16b061424..fdbad1c28 100644
--- a/tests/crawlers/test_bunkr.py
+++ b/tests/crawlers/test_bunkr.py
@@ -1,8 +1,8 @@
import pytest
-from bs4 import BeautifulSoup
from cyberdrop_dl.crawlers import bunkr
from cyberdrop_dl.url_objects import AbsoluteHttpURL
+from cyberdrop_dl.utils import css
def test_album_parser() -> None:
@@ -153,5 +153,5 @@ def test_fix_tumb(url: str, expected: str | None) -> None:
],
)
def test_extract_js_vars(js_value: str, expected: str) -> None:
- soup = BeautifulSoup(f"<script>var jsCDN = {js_value};</script>", "html.parser")
+ soup = css.soup(f"<script>var jsCDN = {js_value};</script>")
assert bunkr._extract_js_vars(soup)["jsCDN"] == expected
diff --git a/tests/crawlers/test_xenforo.py b/tests/crawlers/test_xenforo.py
index 95f404f39..b8d829a7b 100644
--- a/tests/crawlers/test_xenforo.py
+++ b/tests/crawlers/test_xenforo.py
@@ -3,7 +3,6 @@ from __future__ import annotations
from pathlib import Path
import pytest
-from bs4 import BeautifulSoup
from cyberdrop_dl.config.appdata import AppData, AppDirs
from cyberdrop_dl.crawlers import _forum
@@ -13,6 +12,7 @@ from cyberdrop_dl.crawlers.xenforo.celebforum import CelebForumCrawler
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.manager import Manager
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
+from cyberdrop_dl.utils import css
def _item(url: str) -> ScrapeItem:
@@ -43,7 +43,7 @@ def _post(
) -> _forum.ForumPost:
crawler = crawler or TEST_CRAWLER
html = _html(POST_TEMPLATE.format(id=id, message_body=message_body, message_attachments=message_attachments))
- article = BeautifulSoup(html, "html.parser").select("article")[0]
+ article = css.select(css.soup(html), "article")
return _forum.ForumPost.new(article, crawler.SELECTORS.posts)
@@ -585,7 +585,7 @@ def test_get_post_title_thread_w_prefixes() -> None:
<span class="label-append">&nbsp;</span>GunplaMeli</h1>
</div>
""")
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
title = _forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
assert title == "GunplaMeli"
@@ -596,14 +596,14 @@ def test_get_post_title_thread_w_no_prefixes() -> None:
<h1 class="p-title-value">Staged/Fake Japanese Candid Videos from Gcolle/Pcolle or FC2</h1>
</div>
"""
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
title = _forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
assert title == "Staged/Fake Japanese Candid Videos from Gcolle/Pcolle or FC2"
def test_get_post_title_no_title_found() -> None:
html = _html("")
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
with pytest.raises(ScrapeError) as exc_info:
_forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
@@ -613,7 +613,7 @@ def test_get_post_title_no_title_found() -> None:
def test_get_post_title_empty_title_block() -> None:
html = _html("""<h1 class="p-title-value"></h1>""")
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
with pytest.raises(ScrapeError):
_forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
@@ -626,7 +626,7 @@ def test_get_post_title_non_english_chars() -> None:
</h1>
</div>
""")
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
title = _forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
assert title == "㊙️Hcupりおの極秘えち任務🙊💗 (りお❤️❤️❤️) / りお@Rio / rio_hcup_fantia"
@@ -641,7 +641,7 @@ def test_get_post_title_should_strip_new_lines() -> None:
</h1>
</div>
""")
- soup = BeautifulSoup(html, "html.parser")
+ soup = css.soup(html)
title = _forum.get_post_title(soup, xenforo.XenforoCrawler.SELECTORS)
assert title == "㊙️Hcupりおの極秘えち任務🙊💗 (りお❤️❤️❤️) / りお@Rio / rio_hcup_fantia"
diff --git a/tests/next_js/test_next_js.py b/tests/next_js/test_next_js.py
index 2a6f36c25..c9327bff7 100644
--- a/tests/next_js/test_next_js.py
+++ b/tests/next_js/test_next_js.py
@@ -4,19 +4,18 @@ from pathlib import Path
import aiohttp
import pytest
-from bs4 import BeautifulSoup
-from cyberdrop_dl.utils import next_js
+from cyberdrop_dl.utils import css, next_js
TEST_HTML = (Path(__file__).parent / "nextjsv13.html").read_text()
-TEST_SOUP = BeautifulSoup(TEST_HTML, "html.parser")
+TEST_SOUP = css.soup(TEST_HTML)
@pytest.fixture(name="next_data", scope="module")
async def onepace_flight_data() -> next_js.NextJSFlight:
async with aiohttp.ClientSession() as session:
resp = await session.get("https://onepace.net/en/watch")
- soup = BeautifulSoup(await resp.text(), "html.parser")
+ soup = await css.asoup(await resp.text())
return next_js.extract(soup)
diff --git a/tests/test_ddos_guard.py b/tests/test_ddos_guard.py
index edf5a1cac..fe96bf651 100644
--- a/tests/test_ddos_guard.py
+++ b/tests/test_ddos_guard.py
@@ -1,12 +1,12 @@
import dataclasses
import pytest
-from bs4 import BeautifulSoup
from multidict import CIMultiDict
from cyberdrop_dl import ddos_guard
from cyberdrop_dl.clients.request import prepare_headers
from cyberdrop_dl.exceptions import DDOSGuardError
+from cyberdrop_dl.utils import css
anubis_html = """
<!doctype html>
@@ -33,7 +33,7 @@ anubis_html = """
</body>
</html>
"""
-anubis_soup = BeautifulSoup(anubis_html, "html.parser")
+anubis_soup = css.soup(anubis_html)
def test_anubis_detection() -> None:
@@ -65,7 +65,7 @@ async def test_solve_anubis_challenge() -> None:
async def test_ddos_response_should_raise_ddos_guard_error() -> None:
with pytest.raises(DDOSGuardError):
- ddos_guard.check_html(anubis_html)
+ await ddos_guard.check_html(anubis_html)
@dataclasses.dataclass(slots=True)
diff --git a/tests/test_tracebacks.py b/tests/test_tracebacks.py
index 382b54ced..cfc5de114 100644
--- a/tests/test_tracebacks.py
+++ b/tests/test_tracebacks.py
@@ -1,10 +1,10 @@
-from bs4 import BeautifulSoup
from rich import pretty
from rich.traceback import Traceback
from cyberdrop_dl import tracebacks
+from cyberdrop_dl.utils import css
-soup = BeautifulSoup("".join(f"{i}" for i in range(500)), "html.parser")
+soup = css.soup("".join(f"{i}" for i in range(500)))
def test_pretty_truncates_bs4() -> None: