expect_download() context manager. You can intercept downloads, access file metadata, and save files with custom names.
What it does
The script:- Opens a file upload/conversion website (Yandex OCR translator)
- Uploads an image file
- Triggers a download by clicking a button
- Intercepts the download
- Decodes the file data and saves it with the suggested filename
Complete code
Key techniques
Context manager pattern
Useasync with to handle the browser lifecycle:
Download interception
Wrap the download-triggering action inexpect_download():
Download metadata
Access information about the downloaded file:Data URL decoding
For data URLs (base64-encoded content), decode and save:Mouse click
Usemouse_click() for more realistic clicking behavior:
.click().
Running the example
- Update the
path_imagevariable with your actual image path - Save the code to a file (e.g.,
download_file.py) - Run it with Python:
- The downloaded file will be saved in the current directory
Use cases
- Automated downloads: Download reports, exports, or generated files
- File validation: Verify downloaded content matches expectations
- Custom file handling: Process or rename files based on metadata
- Batch downloads: Loop through multiple downloads in a workflow
- Testing: Verify download functionality works correctly
Important notes
Data URLs vs regular downloads
Some downloads return data URLs (base64-encoded content in the URL itself), while others initiate regular file downloads. This example handles data URLs. For regular file downloads, you may need to configure download behavior differently.Timing considerations
The example usesasyncio.sleep(3) to wait for file processing. In production, consider using more robust waiting strategies:
File paths
Use raw strings (r"path") or forward slashes for file paths to avoid issues with backslashes on Windows: