同步完整源码 - 2026-05-24
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
from crawlee.crawlers import AdaptivePlaywrightCrawler, AdaptivePlaywrightCrawlingContext
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = AdaptivePlaywrightCrawler.with_parsel_static_parser()
|
||||
|
||||
@crawler.router.default_handler
|
||||
async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None:
|
||||
# Locate element h2 within 5 seconds
|
||||
h2 = await context.query_selector_one('h2', timedelta(milliseconds=5000))
|
||||
# Do stuff with element found by the selector
|
||||
context.log.info(h2)
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import AdaptivePlaywrightCrawler
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(
|
||||
# Arguments relevant only for PlaywrightCrawler
|
||||
playwright_crawler_specific_kwargs={
|
||||
'headless': False,
|
||||
'browser_type': 'chromium',
|
||||
},
|
||||
# Common arguments relevant to all crawlers
|
||||
max_crawl_depth=5,
|
||||
)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee.crawlers import AdaptivePlaywrightCrawler
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = AdaptivePlaywrightCrawler.with_parsel_static_parser(
|
||||
# Arguments relevant only for PlaywrightCrawler
|
||||
playwright_crawler_specific_kwargs={
|
||||
'headless': False,
|
||||
'browser_type': 'chromium',
|
||||
},
|
||||
# Common arguments relevant to all crawlers
|
||||
max_crawl_depth=5,
|
||||
)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
import asyncio
|
||||
|
||||
from crawlee import Request
|
||||
from crawlee._types import RequestHandlerRunResult
|
||||
from crawlee.crawlers import (
|
||||
AdaptivePlaywrightCrawler,
|
||||
RenderingType,
|
||||
RenderingTypePrediction,
|
||||
RenderingTypePredictor,
|
||||
)
|
||||
|
||||
|
||||
class CustomRenderingTypePredictor(RenderingTypePredictor):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
|
||||
self._learning_data = list[tuple[Request, RenderingType]]()
|
||||
|
||||
def predict(self, request: Request) -> RenderingTypePrediction:
|
||||
# Some custom logic that produces some `RenderingTypePrediction`
|
||||
# based on the `request` input.
|
||||
rendering_type: RenderingType = (
|
||||
'static' if 'abc' in request.url else 'client only'
|
||||
)
|
||||
|
||||
return RenderingTypePrediction(
|
||||
# Recommends `static` rendering type -> HTTP-based sub crawler will be used.
|
||||
rendering_type=rendering_type,
|
||||
# Recommends that both sub crawlers should run with 20% chance. When both sub
|
||||
# crawlers are running, the predictor can compare results and learn.
|
||||
# High number means that predictor is not very confident about the
|
||||
# `rendering_type`, low number means that predictor is very confident.
|
||||
detection_probability_recommendation=0.2,
|
||||
)
|
||||
|
||||
def store_result(self, request: Request, rendering_type: RenderingType) -> None:
|
||||
# This function allows predictor to store new learning data and retrain itself
|
||||
# if needed. `request` is input for prediction and `rendering_type` is the correct
|
||||
# prediction.
|
||||
self._learning_data.append((request, rendering_type))
|
||||
# retrain
|
||||
|
||||
|
||||
def result_checker(result: RequestHandlerRunResult) -> bool:
|
||||
# Some function that inspects produced `result` and returns `True` if the result
|
||||
# is correct.
|
||||
return bool(result) # Check something on result
|
||||
|
||||
|
||||
def result_comparator(
|
||||
result_1: RequestHandlerRunResult, result_2: RequestHandlerRunResult
|
||||
) -> bool:
|
||||
# Some function that inspects two results and returns `True` if they are
|
||||
# considered equivalent. It is used when comparing results produced by HTTP-based
|
||||
# sub crawler and playwright based sub crawler.
|
||||
return (
|
||||
result_1.push_data_calls == result_2.push_data_calls
|
||||
) # For example compare `push_data` calls.
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = AdaptivePlaywrightCrawler.with_parsel_static_parser(
|
||||
rendering_type_predictor=CustomRenderingTypePredictor(),
|
||||
result_checker=result_checker,
|
||||
result_comparator=result_comparator,
|
||||
)
|
||||
|
||||
# ...
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
import asyncio
|
||||
|
||||
from playwright.async_api import Route
|
||||
|
||||
from crawlee.crawlers import (
|
||||
AdaptivePlaywrightCrawler,
|
||||
AdaptivePlaywrightPreNavCrawlingContext,
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser()
|
||||
|
||||
@crawler.pre_navigation_hook
|
||||
async def hook(context: AdaptivePlaywrightPreNavCrawlingContext) -> None:
|
||||
"""Hook executed both in static sub crawler and playwright sub crawler.
|
||||
|
||||
Trying to access `context.page` in this hook would raise `AdaptiveContextError`
|
||||
for pages crawled without playwright.
|
||||
"""
|
||||
context.log.info(f'pre navigation hook for: {context.request.url}')
|
||||
|
||||
@crawler.pre_navigation_hook(playwright_only=True)
|
||||
async def hook_playwright(context: AdaptivePlaywrightPreNavCrawlingContext) -> None:
|
||||
"""Hook executed only in playwright sub crawler."""
|
||||
|
||||
async def some_routing_function(route: Route) -> None:
|
||||
await route.continue_()
|
||||
|
||||
await context.page.route('*/**', some_routing_function)
|
||||
context.log.info(
|
||||
f'Playwright only pre navigation hook for: {context.request.url}'
|
||||
)
|
||||
|
||||
await crawler.run(['https://crawlee.dev/'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user