Skip to content

Commit cb8888d

Browse files
committed
report robots.txt skips and fetch each robots.txt once in AdaptivePlaywrightCrawler
1 parent aa591bb commit cb8888d

2 files changed

Lines changed: 63 additions & 1 deletion

File tree

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848

4949
from typing_extensions import Unpack
5050

51-
from crawlee._types import UseStateFunction
51+
from crawlee._types import SkippedReason, UseStateFunction
5252
from crawlee.crawlers._basic._basic_crawler import _BasicCrawlerOptions
5353

5454

@@ -221,6 +221,13 @@ async def adaptive_post_navigation_hook_pw(context: PlaywrightPostNavCrawlingCon
221221
static_crawler.post_navigation_hook(adaptive_post_navigation_hook_static)
222222
playwright_crawler.post_navigation_hook(adaptive_post_navigation_hook_pw)
223223

224+
# The sub crawlers check links against robots.txt in `enqueue_links`. They share the robots.txt cache of this
225+
# crawler, so that each file is fetched once, and report the links they skip to its `on_skipped_request`.
226+
for sub_crawler in (static_crawler, playwright_crawler):
227+
sub_crawler._robots_txt_file_cache = self._robots_txt_file_cache # noqa: SLF001
228+
sub_crawler._robots_txt_lock = self._robots_txt_lock # noqa: SLF001
229+
sub_crawler.on_skipped_request(self._report_skipped_request)
230+
224231
self._additional_context_managers = [
225232
*self._additional_context_managers,
226233
self.rendering_type_predictor,
@@ -285,6 +292,10 @@ def with_parsel_static_parser(
285292
**kwargs,
286293
)
287294

295+
async def _report_skipped_request(self, url: str, reason: SkippedReason) -> None:
296+
if self._on_skipped_request:
297+
await self._on_skipped_request(url, reason)
298+
288299
async def _crawl_one(
289300
self,
290301
rendering_type: RenderingType,

‎tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from typing_extensions import override
1616

1717
from crawlee import ConcurrencySettings, Request
18+
from crawlee._utils.robots import RobotsTxtFile
1819
from crawlee.crawlers import (
1920
AdaptivePlaywrightCrawler,
2021
AdaptivePlaywrightCrawlingContext,
@@ -43,6 +44,8 @@
4344

4445
from yarl import URL
4546

47+
from crawlee._types import SkippedReason
48+
4649

4750
_H1_TEXT = 'Static'
4851
_H2_TEXT = 'Only in browser'
@@ -695,6 +698,54 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None:
695698
mocked_browser_handler.assert_called_once_with()
696699

697700

701+
@pytest.mark.parametrize(
702+
'rendering_type',
703+
[
704+
pytest.param('static', id='static'),
705+
pytest.param('client only', id='browser'),
706+
],
707+
)
708+
async def test_on_skipped_request(server_url: URL, rendering_type: RenderingType) -> None:
709+
"""Links that a sub crawler skips in `enqueue_links` because of robots.txt reach the callback of the crawler."""
710+
crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(
711+
rendering_type_predictor=_SimpleRenderingTypePredictor(
712+
rendering_types=cycle([rendering_type]), detection_probability_recommendation=cycle([0])
713+
),
714+
respect_robots_txt_file=True,
715+
)
716+
skip = Mock()
717+
718+
@crawler.router.default_handler
719+
async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None:
720+
await context.enqueue_links()
721+
722+
@crawler.on_skipped_request
723+
async def skipped_hook(url: str, _reason: SkippedReason) -> None:
724+
skip(url)
725+
726+
await crawler.run([str(server_url / 'start_enqueue')])
727+
728+
skip.assert_has_calls([call(str(server_url / f'page_{index}')) for index in range(1, 5)], any_order=True)
729+
730+
731+
async def test_fetches_robots_txt_once(server_url: URL, monkeypatch: pytest.MonkeyPatch) -> None:
732+
"""The crawler and its sub crawlers fetch the robots.txt file of a domain once, detection runs included."""
733+
find = AsyncMock(wraps=RobotsTxtFile.find)
734+
monkeypatch.setattr(RobotsTxtFile, 'find', find)
735+
crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(
736+
rendering_type_predictor=_SimpleRenderingTypePredictor(detection_probability_recommendation=cycle([1])),
737+
respect_robots_txt_file=True,
738+
)
739+
740+
@crawler.router.default_handler
741+
async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None:
742+
await context.enqueue_links()
743+
744+
await crawler.run([str(server_url / 'start_enqueue')])
745+
746+
find.assert_awaited_once()
747+
748+
698749
async def test_adaptive_context_query_selector_beautiful_soup(test_urls: list[str]) -> None:
699750
"""Test that `context.query_selector_one` works regardless of the crawl type for BeautifulSoup variant.
700751

0 commit comments

Comments
 (0)