Repository navigation
feat: BeautifulSoupCrawler #107
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1cf1fc5
feat: BeautifulSoupCrawler
janbuchar 6d12459
Initial http crawler tests
janbuchar 3b98cd8
Improve error handling in ContextPipeline
janbuchar 38135b7
Retry http errors
janbuchar eb2e561
Update TODO comment
janbuchar 97c8fd7
Add beautifulsoup test
janbuchar e3cbccb
Install beautifulsoup in dev mode
janbuchar fa9b922
Apply suggestions from code review
janbuchar dc4ea3d
Fix Makefile syntax error
janbuchar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| from .beautifulsoup_crawler import BeautifulSoupCrawler, BeautifulSoupCrawlingContext |
97 changes: 97 additions & 0 deletions
97
src/crawlee/beautifulsoup_crawler/beautifulsoup_crawler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from datetime import timedelta | ||
| from typing import TYPE_CHECKING, AsyncGenerator, Awaitable, Callable, Iterable, Literal | ||
|
|
||
| import httpx | ||
|
|
||
| from crawlee.basic_crawler.basic_crawler import BasicCrawler | ||
| from crawlee.basic_crawler.context_pipeline import ContextPipeline | ||
| from crawlee.beautifulsoup_crawler.types import BeautifulSoupCrawlingContext | ||
| from crawlee.http_crawler.http_crawler import make_http_request | ||
| from crawlee.http_crawler.types import HttpCrawlingContext | ||
|
|
||
| if TYPE_CHECKING: | ||
| from datetime import timedelta | ||
|
|
||
| from crawlee.autoscaling.autoscaled_pool import ConcurrencySettings | ||
| from crawlee.basic_crawler.types import BasicCrawlingContext | ||
| from crawlee.configuration import Configuration | ||
| from crawlee.storages.request_provider import RequestProvider | ||
|
|
||
|
|
||
| class BeautifulSoupCrawler(BasicCrawler[BeautifulSoupCrawlingContext]): | ||
| """A crawler that fetches the request URL using `httpx` and parses the result with `BeautifulSoup`.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| parser: Literal['html.parser', 'lxml', 'xml', 'html5lib'] = 'lxml', | ||
| request_provider: RequestProvider, | ||
| router: Callable[[BeautifulSoupCrawlingContext], Awaitable[None]] | None = None, | ||
| concurrency_settings: ConcurrencySettings | None = None, | ||
| configuration: Configuration | None = None, | ||
| request_handler_timeout: timedelta | None = None, | ||
| additional_http_error_status_codes: Iterable[int] = (), | ||
| ignore_http_error_status_codes: Iterable[int] = (), | ||
| ) -> None: | ||
| """Initialize the BeautifulSoupCrawler. | ||
|
|
||
| Args: | ||
| parser: The type of parser that should be used by BeautifulSoup | ||
|
|
||
| request_provider: Provides requests to be processed | ||
|
|
||
| router: A callable to which request handling is delegated | ||
|
|
||
| concurrency_settings: Allows fine-tuning concurrency levels | ||
|
|
||
| configuration: Crawler configuration | ||
|
|
||
| request_handler_timeout: How long is a single request handler allowed to run | ||
|
|
||
| additional_http_error_status_codes: HTTP status codes that should be considered errors (and trigger a retry) | ||
|
|
||
| ignore_http_error_status_codes: HTTP status codes that are normally considered errors but we want to treat | ||
| them as successful | ||
| """ | ||
| context_pipeline = ContextPipeline().compose(self._make_http_request).compose(self._parse_http_response) | ||
|
|
||
| self._client = httpx.AsyncClient() | ||
| self._parser = parser | ||
|
|
||
| self._additional_http_error_status_codes = set(additional_http_error_status_codes) | ||
| self._ignore_http_error_status_codes = set(ignore_http_error_status_codes) | ||
|
|
||
| basic_crawler_kwargs = {} | ||
|
|
||
| if request_handler_timeout is not None: | ||
| basic_crawler_kwargs['request_handler_timeout'] = request_handler_timeout | ||
|
|
||
| super().__init__( | ||
| request_provider=request_provider, | ||
| router=router, | ||
| concurrency_settings=concurrency_settings, | ||
| configuration=configuration, | ||
| _context_pipeline=context_pipeline, | ||
| **basic_crawler_kwargs, # type: ignore | ||
| ) | ||
|
|
||
| async def _make_http_request(self, context: BasicCrawlingContext) -> AsyncGenerator[HttpCrawlingContext, None]: | ||
| result = await make_http_request( | ||
| self._client, | ||
| context.request, | ||
| additional_http_error_status_codes=self._additional_http_error_status_codes, | ||
| ignore_http_error_status_codes=self._ignore_http_error_status_codes, | ||
| ) | ||
|
|
||
| yield HttpCrawlingContext(request=context.request, http_response=result.http_response) | ||
|
|
||
| async def _parse_http_response( | ||
| self, context: HttpCrawlingContext | ||
| ) -> AsyncGenerator[BeautifulSoupCrawlingContext, None]: | ||
| from bs4 import BeautifulSoup | ||
|
|
||
| soup = await asyncio.to_thread(lambda: BeautifulSoup(context.http_response.read(), self._parser)) | ||
| yield BeautifulSoupCrawlingContext(request=context.request, http_response=context.http_response, soup=soup) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from crawlee.basic_crawler.types import BasicCrawlingContext | ||
| from crawlee.http_crawler.types import HttpCrawlResult | ||
|
|
||
| if TYPE_CHECKING: | ||
| from bs4 import BeautifulSoup | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class BeautifulSoupCrawlingContext(HttpCrawlResult, BasicCrawlingContext): | ||
| """Crawling context used by BeautifulSoupCrawler.""" | ||
| soup: BeautifulSoup |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.