-
Notifications
You must be signed in to change notification settings - Fork 777
feat: add FileDownloadCrawler
#2043
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
Open
Mantisus
wants to merge
2
commits into
apify:master
Choose a base branch
from
Mantisus:file-downloaw-crawler
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+532
−3
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import asyncio | ||
|
|
||
| from yarl import URL | ||
|
|
||
| from crawlee.crawlers import FileDownloadCrawler, FileDownloadCrawlingContext | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| # FileDownloadCrawler downloads files with plain HTTP requests and accepts | ||
| # any content type. | ||
| crawler = FileDownloadCrawler( | ||
| # Limit the crawl to max requests. Remove or increase it for crawling all links. | ||
| max_requests_per_crawl=10, | ||
| ) | ||
|
|
||
| # Define the default request handler, which will be called for every request. | ||
| @crawler.router.default_handler | ||
| async def request_handler(context: FileDownloadCrawlingContext) -> None: | ||
| context.log.info(f'Downloading {context.request.url} ...') | ||
|
|
||
| # Read the whole file into memory. | ||
| content = await context.http_response.read() | ||
|
|
||
| # Save the file to the default key-value store with the server's content type. | ||
| kvs = await context.get_key_value_store() | ||
| file_name = URL(context.request.url).name | ||
| await kvs.set_value( | ||
| key=file_name, | ||
| value=content, | ||
| content_type=context.http_response.headers.get('content-type'), | ||
| ) | ||
|
|
||
| # Run the crawler with the list of files to download. | ||
| await crawler.run( | ||
| [ | ||
| 'https://pdfobject.com/pdf/sample.pdf', | ||
| 'https://crawlee.dev/assets/images/gradcracker-scraper-caefb62d1c150c4209a6e564c052fa41.webp', | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| asyncio.run(main()) |
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,49 @@ | ||
| import asyncio | ||
| from datetime import timedelta | ||
| from pathlib import Path | ||
|
|
||
| from yarl import URL | ||
|
|
||
| from crawlee.crawlers import FileDownloadCrawler, FileDownloadCrawlingContext | ||
|
|
||
| DOWNLOAD_DIR = Path('downloads') | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| # With stream=True, the request handler receives a response whose body has not | ||
| # been read yet. | ||
| crawler = FileDownloadCrawler( | ||
| stream=True, | ||
| # Bounds establishing the connection and receiving the response headers. | ||
| navigation_timeout=timedelta(minutes=5), | ||
| # The body is downloaded inside the handler, so this bounds the transfer itself. | ||
| request_handler_timeout=timedelta(minutes=5), | ||
| # Limit the crawl to max requests. Remove or increase it for crawling all links. | ||
| max_requests_per_crawl=10, | ||
| ) | ||
|
|
||
| # Define the default request handler, which will be called for every request. | ||
| @crawler.router.default_handler | ||
| async def request_handler(context: FileDownloadCrawlingContext) -> None: | ||
| context.log.info(f'Downloading {context.request.url} ...') | ||
|
|
||
| file_name = URL(context.request.url).name | ||
|
|
||
| # Write each chunk to disk as it arrives, without buffering the whole file. | ||
| with (DOWNLOAD_DIR / file_name).open('wb') as file: | ||
| async for chunk in context.http_response.read_stream(): | ||
| file.write(chunk) | ||
|
|
||
| context.log.info(f'Saved {file_name}') | ||
|
|
||
| # Run the crawler with the list of files to download. | ||
| await crawler.run( | ||
| [ | ||
| 'https://samplelib.com/mp4/sample-15s-720p.mp4', | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| DOWNLOAD_DIR.mkdir(exist_ok=True) | ||
| asyncio.run(main()) |
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,25 @@ | ||
| --- | ||
| id: file-download | ||
| title: Download files | ||
| --- | ||
|
|
||
| import ApiLink from '@site/src/components/ApiLink'; | ||
| import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock'; | ||
| import CodeBlock from '@theme/CodeBlock'; | ||
|
|
||
| import FileDownloadExample from '!!raw-loader!roa-loader!./code_examples/file_download.py'; | ||
| import FileDownloadStreamExample from '!!raw-loader!./code_examples/file_download_stream.py'; | ||
|
|
||
| This example demonstrates how to use <ApiLink to="class/FileDownloadCrawler">`FileDownloadCrawler`</ApiLink> to download files such as PDFs, images or videos with plain HTTP requests. The crawler doesn't parse the response body, so any content type is accepted. Each downloaded file is saved to the default <ApiLink to="class/KeyValueStore">`KeyValueStore`</ApiLink> together with the content type reported by the server. | ||
|
|
||
| <RunnableCodeBlock className="language-python" language="python"> | ||
| {FileDownloadExample} | ||
| </RunnableCodeBlock> | ||
|
|
||
| ## Streaming large files | ||
|
|
||
| Buffering a whole file in memory doesn't scale to large downloads. Construct the crawler with `stream=True` and the request handler receives a response whose body hasn't been read yet. Consume it in chunks with <ApiLink to="class/HttpResponse#read_stream">`read_stream()`</ApiLink> and write each chunk to disk as it arrives. | ||
|
|
||
| <CodeBlock className="language-python" language="python"> | ||
| {FileDownloadStreamExample} | ||
| </CodeBlock> |
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,7 @@ | ||
| from ._file_download_crawler import FileDownloadCrawler | ||
| from ._file_download_crawling_context import FileDownloadCrawlingContext | ||
|
|
||
| __all__ = [ | ||
| 'FileDownloadCrawler', | ||
| 'FileDownloadCrawlingContext', | ||
| ] |
Oops, something went wrong.
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.