Skip to content

Commit d57c6a0

Browse files
authored
fix: Name the extra to install in optional-dependency import errors (#2208)
Accessing a symbol guarded by `try_import` without its extra installed raises an `ImportError` that now also names the extra to install: ``` No module named 'bs4'. Install the optional 'beautifulsoup' extra to use it: pip install 'crawlee[beautifulsoup]' ``` `try_import` takes a required `extra_name`, and every guarded site passes it. `SqlStorageClient` passes the three SQL extras, so the message lists them and shows one install command. The hint is added only for a `ModuleNotFoundError`; the `ImportError` re-raised by a nested guard (e.g. `crawlee.crawlers` re-exporting `crawlee.crawlers._beautifulsoup`) already carries it and is kept as is. *✍️ Drafted by Claude Code*
1 parent 7e71d70 commit d57c6a0

12 files changed

Lines changed: 132 additions & 42 deletions

File tree

‎src/crawlee/_utils/try_import.py‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
1+
from __future__ import annotations
2+
13
import sys
2-
from collections.abc import Iterator
34
from contextlib import contextmanager
45
from dataclasses import dataclass
56
from types import ModuleType
6-
from typing import Any
7+
from typing import TYPE_CHECKING
8+
9+
if TYPE_CHECKING:
10+
from collections.abc import Iterator
11+
from typing import Any
712

813

914
@contextmanager
10-
def try_import(module_name: str, *symbol_names: str) -> Iterator[None]:
15+
def try_import(module_name: str, *symbol_names: str, extra_name: str | list[str]) -> Iterator[None]:
1116
"""Context manager to attempt importing symbols into a module.
1217
13-
If an `ImportError` is raised during the import, the symbol will be replaced with a `FailedImport` object.
18+
If an `ImportError` is raised during the import, the symbols are replaced with `FailedImport` objects. When the
19+
error is a `ModuleNotFoundError`, the message also names the optional extra (or one of several) that installs the
20+
missing dependency. Other import errors, including those raised by a nested guard, keep their message as is.
1421
"""
1522
try:
1623
yield
1724
except ImportError as e:
25+
message = e.args[0]
26+
if isinstance(e, ModuleNotFoundError):
27+
message = f'{message}. {_get_install_hint(extra_name)}'
1828
for symbol_name in symbol_names:
19-
setattr(sys.modules[module_name], symbol_name, FailedImport(e.args[0]))
29+
setattr(sys.modules[module_name], symbol_name, FailedImport(message))
30+
31+
32+
def _get_install_hint(extra_name: str | list[str]) -> str:
33+
"""Build the sentence telling the user which extra installs the missing optional dependency."""
34+
if isinstance(extra_name, str):
35+
return f"Install the optional '{extra_name}' extra to use it: pip install 'crawlee[{extra_name}]'"
36+
extras = ', '.join(f"'{name}'" for name in extra_name)
37+
return f"Install one of the optional extras {extras} to use it, e.g. pip install 'crawlee[{extra_name[0]}]'"
2038

2139

2240
def install_import_hook(module_name: str) -> None:

‎src/crawlee/browsers/__init__.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@
88

99
# The following imports are wrapped in try_import to handle optional dependencies,
1010
# ensuring the module can still function even if these dependencies are missing.
11-
with _try_import(__name__, 'BrowserPool'):
11+
with _try_import(__name__, 'BrowserPool', extra_name='playwright'):
1212
from ._browser_pool import BrowserPool
13-
with _try_import(__name__, 'PlaywrightBrowserController'):
13+
with _try_import(__name__, 'PlaywrightBrowserController', extra_name='playwright'):
1414
from ._playwright_browser_controller import PlaywrightBrowserController
15-
with _try_import(__name__, 'PlaywrightBrowserPlugin'):
15+
with _try_import(__name__, 'PlaywrightBrowserPlugin', extra_name='playwright'):
1616
from ._playwright_browser_plugin import PlaywrightBrowserPlugin
17-
with _try_import(__name__, 'PlaywrightPersistentBrowser'):
17+
with _try_import(__name__, 'PlaywrightPersistentBrowser', extra_name='playwright'):
1818
from ._playwright_browser import PlaywrightPersistentBrowser
1919

20-
with _try_import(__name__, 'StagehandBrowserController'):
20+
with _try_import(__name__, 'StagehandBrowserController', extra_name='stagehand'):
2121
from ._stagehand_browser_controller import StagehandBrowserController
22-
with _try_import(__name__, 'StagehandBrowserPlugin'):
22+
with _try_import(__name__, 'StagehandBrowserPlugin', extra_name='stagehand'):
2323
from ._stagehand_browser_plugin import StagehandBrowserPlugin
24-
with _try_import(__name__, 'StagehandOptions', 'StagehandPage'):
24+
with _try_import(__name__, 'StagehandOptions', 'StagehandPage', extra_name='stagehand'):
2525
from ._stagehand_types import StagehandOptions, StagehandPage
2626

2727

‎src/crawlee/crawlers/__init__.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,16 @@
1010

1111
# The following imports use try_import to handle optional dependencies, as they may not always be available.
1212

13-
with _try_import(__name__, 'BeautifulSoupCrawler', 'BeautifulSoupCrawlingContext', 'BeautifulSoupParserType'):
13+
with _try_import(
14+
__name__,
15+
'BeautifulSoupCrawler',
16+
'BeautifulSoupCrawlingContext',
17+
'BeautifulSoupParserType',
18+
extra_name='beautifulsoup',
19+
):
1420
from ._beautifulsoup import BeautifulSoupCrawler, BeautifulSoupCrawlingContext, BeautifulSoupParserType
1521

16-
with _try_import(__name__, 'ParselCrawler', 'ParselCrawlingContext'):
22+
with _try_import(__name__, 'ParselCrawler', 'ParselCrawlingContext', extra_name='parsel'):
1723
from ._parsel import ParselCrawler, ParselCrawlingContext
1824

1925
with _try_import(
@@ -22,6 +28,7 @@
2228
'PlaywrightCrawlingContext',
2329
'PlaywrightPostNavCrawlingContext',
2430
'PlaywrightPreNavCrawlingContext',
31+
extra_name='playwright',
2532
):
2633
from ._playwright import (
2734
PlaywrightCrawler,
@@ -40,6 +47,7 @@
4047
'RenderingType',
4148
'RenderingTypePrediction',
4249
'RenderingTypePredictor',
50+
extra_name='adaptive-crawler',
4351
):
4452
from ._adaptive_playwright import (
4553
AdaptivePlaywrightCrawler,
@@ -58,6 +66,7 @@
5866
'StagehandCrawlingContext',
5967
'StagehandPostNavCrawlingContext',
6068
'StagehandPreNavCrawlingContext',
69+
extra_name='stagehand',
6170
):
6271
from ._stagehand import (
6372
StagehandCrawler,
@@ -80,6 +89,7 @@
8089
'BasePydanticAiHtmlDistiller',
8190
'BasePydanticAiHtmlExtractor',
8291
'get_basic_http_cleaner',
92+
extra_name='pydantic-ai',
8393
):
8494
from ._pydantic_ai import (
8595
BasePydanticAiHtmlDistiller,

‎src/crawlee/crawlers/_adaptive_playwright/__init__.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212

1313
# The following imports are wrapped in try_import to handle optional dependencies,
1414
# ensuring the module can still function even if these dependencies are missing.
15-
with _try_import(__name__, 'RenderingType', 'RenderingTypePrediction', 'RenderingTypePredictor'):
15+
with _try_import(
16+
__name__, 'RenderingType', 'RenderingTypePrediction', 'RenderingTypePredictor', extra_name='adaptive-crawler'
17+
):
1618
from ._rendering_type_predictor import RenderingType, RenderingTypePrediction, RenderingTypePredictor
17-
with _try_import(__name__, 'AdaptivePlaywrightCrawler'):
19+
with _try_import(__name__, 'AdaptivePlaywrightCrawler', extra_name='adaptive-crawler'):
1820
from ._adaptive_playwright_crawler import AdaptivePlaywrightCrawler
19-
with _try_import(__name__, 'AdaptivePlaywrightCrawlerStatisticState'):
21+
with _try_import(__name__, 'AdaptivePlaywrightCrawlerStatisticState', extra_name='adaptive-crawler'):
2022
from ._adaptive_playwright_crawler import AdaptivePlaywrightCrawlerStatisticState
2123

2224
__all__ = [

‎src/crawlee/crawlers/_beautifulsoup/__init__.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55

66
# The following imports are wrapped in try_import to handle optional dependencies,
77
# ensuring the module can still function even if these dependencies are missing.
8-
with _try_import(__name__, 'BeautifulSoupCrawler'):
8+
with _try_import(__name__, 'BeautifulSoupCrawler', extra_name='beautifulsoup'):
99
from ._beautifulsoup_crawler import BeautifulSoupCrawler
10-
with _try_import(__name__, 'BeautifulSoupCrawlingContext'):
10+
with _try_import(__name__, 'BeautifulSoupCrawlingContext', extra_name='beautifulsoup'):
1111
from ._beautifulsoup_crawling_context import BeautifulSoupCrawlingContext
12-
with _try_import(__name__, 'BeautifulSoupParserType'):
12+
with _try_import(__name__, 'BeautifulSoupParserType', extra_name='beautifulsoup'):
1313
from ._beautifulsoup_parser import BeautifulSoupParserType
1414

1515
__all__ = [

‎src/crawlee/crawlers/_parsel/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55

66
# The following imports are wrapped in try_import to handle optional dependencies,
77
# ensuring the module can still function even if these dependencies are missing.
8-
with _try_import(__name__, 'ParselCrawler'):
8+
with _try_import(__name__, 'ParselCrawler', extra_name='parsel'):
99
from ._parsel_crawler import ParselCrawler
10-
with _try_import(__name__, 'ParselCrawlingContext'):
10+
with _try_import(__name__, 'ParselCrawlingContext', extra_name='parsel'):
1111
from ._parsel_crawling_context import ParselCrawlingContext
1212

1313
__all__ = [

‎src/crawlee/crawlers/_playwright/__init__.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55

66
# The following imports are wrapped in try_import to handle optional dependencies,
77
# ensuring the module can still function even if these dependencies are missing.
8-
with _try_import(__name__, 'PlaywrightCrawler'):
8+
with _try_import(__name__, 'PlaywrightCrawler', extra_name='playwright'):
99
from ._playwright_crawler import PlaywrightCrawler
10-
with _try_import(__name__, 'PlaywrightCrawlingContext'):
10+
with _try_import(__name__, 'PlaywrightCrawlingContext', extra_name='playwright'):
1111
from ._playwright_crawling_context import PlaywrightCrawlingContext
12-
with _try_import(__name__, 'PlaywrightPreNavCrawlingContext'):
12+
with _try_import(__name__, 'PlaywrightPreNavCrawlingContext', extra_name='playwright'):
1313
from ._playwright_pre_nav_crawling_context import PlaywrightPreNavCrawlingContext
14-
with _try_import(__name__, 'PlaywrightPostNavCrawlingContext'):
14+
with _try_import(__name__, 'PlaywrightPostNavCrawlingContext', extra_name='playwright'):
1515
from ._playwright_post_nav_crawling_context import PlaywrightPostNavCrawlingContext
1616

1717
__all__ = [

‎src/crawlee/crawlers/_pydantic_ai/__init__.py‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,27 @@
55

66
# The following imports are wrapped in try_import to handle optional dependencies (the `pydantic-ai` extra),
77
# ensuring the module can still function even if these dependencies are missing.
8-
with _try_import(__name__, 'PydanticAiCrawler'):
8+
with _try_import(__name__, 'PydanticAiCrawler', extra_name='pydantic-ai'):
99
from ._pydantic_ai_crawler import PydanticAiCrawler
10-
with _try_import(__name__, 'PydanticAiCrawlingContext'):
10+
with _try_import(__name__, 'PydanticAiCrawlingContext', extra_name='pydantic-ai'):
1111
from ._pydantic_ai_crawling_context import PydanticAiCrawlingContext
12-
with _try_import(__name__, 'BasePydanticAiHtmlExtractor'):
12+
with _try_import(__name__, 'BasePydanticAiHtmlExtractor', extra_name='pydantic-ai'):
1313
from ._base_extractor import BasePydanticAiHtmlExtractor
14-
with _try_import(__name__, 'PydanticAiDirectExtractor'):
14+
with _try_import(__name__, 'PydanticAiDirectExtractor', extra_name='pydantic-ai'):
1515
from ._direct_extractor import PydanticAiDirectExtractor
16-
with _try_import(__name__, 'PydanticAiSelectorExtractor'):
16+
with _try_import(__name__, 'PydanticAiSelectorExtractor', extra_name='pydantic-ai'):
1717
from ._selector_extractor import PydanticAiSelectorExtractor
18-
with _try_import(__name__, 'BasePydanticAiHtmlDistiller'):
18+
with _try_import(__name__, 'BasePydanticAiHtmlDistiller', extra_name='pydantic-ai'):
1919
from ._base_distiller import BasePydanticAiHtmlDistiller
20-
with _try_import(__name__, 'PydanticAiCleanHtmlDistiller'):
20+
with _try_import(__name__, 'PydanticAiCleanHtmlDistiller', extra_name='pydantic-ai'):
2121
from ._clean_html_distiller import PydanticAiCleanHtmlDistiller
22-
with _try_import(__name__, 'PydanticAiSkeletonDistiller'):
22+
with _try_import(__name__, 'PydanticAiSkeletonDistiller', extra_name='pydantic-ai'):
2323
from ._skeleton_distiller import PydanticAiSkeletonDistiller
24-
with _try_import(__name__, 'PydanticAiHtmlDistiller', 'PydanticAiHtmlExtractor', 'PydanticAiUsageStats'):
24+
with _try_import(
25+
__name__, 'PydanticAiHtmlDistiller', 'PydanticAiHtmlExtractor', 'PydanticAiUsageStats', extra_name='pydantic-ai'
26+
):
2527
from ._types import PydanticAiHtmlDistiller, PydanticAiHtmlExtractor, PydanticAiUsageStats
26-
with _try_import(__name__, 'get_basic_http_cleaner'):
28+
with _try_import(__name__, 'get_basic_http_cleaner', extra_name='pydantic-ai'):
2729
from ._utils import get_basic_http_cleaner
2830

2931
__all__ = [

‎src/crawlee/crawlers/_stagehand/__init__.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55

66
# The following imports are wrapped in try_import to handle optional dependencies,
77
# ensuring the module can still function even if these dependencies are missing.
8-
with _try_import(__name__, 'StagehandCrawler'):
8+
with _try_import(__name__, 'StagehandCrawler', extra_name='stagehand'):
99
from ._stagehand_crawler import StagehandCrawler
1010
with _try_import(
11-
__name__, 'StagehandCrawlingContext', 'StagehandPostNavCrawlingContext', 'StagehandPreNavCrawlingContext'
11+
__name__,
12+
'StagehandCrawlingContext',
13+
'StagehandPostNavCrawlingContext',
14+
'StagehandPreNavCrawlingContext',
15+
extra_name='stagehand',
1216
):
1317
from ._stagehand_crawling_context import (
1418
StagehandCrawlingContext,

‎src/crawlee/http_clients/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99

1010
# The following imports are wrapped in try_import to handle optional dependencies,
1111
# ensuring the module can still function even if these dependencies are missing.
12-
with _try_import(__name__, 'CurlImpersonateHttpClient'):
12+
with _try_import(__name__, 'CurlImpersonateHttpClient', extra_name='curl-impersonate'):
1313
from ._curl_impersonate import CurlImpersonateHttpClient
1414

15-
with _try_import(__name__, 'HttpxHttpClient'):
15+
with _try_import(__name__, 'HttpxHttpClient', extra_name='httpx'):
1616
from ._httpx import HttpxHttpClient
1717

1818

0 commit comments

Comments
 (0)