Other Options:
• PayPal
• Ko-Fi
For extended features, enterprise integrations, or custom commercial licensing, please contact EchterAlsFakeBS@proton.me.
Installation
Install from PyPI using pip:
pip install unofficial-api-for-porntrex
eaf-base-api>=4.0.0. The compatible networking core is installed automatically.
Quick Start
All operations are asynchronous and should run within an async context:
import asyncio
from porntrex_api import Client
from base_api import DownloadConfigRAW
async def main():
client = Client()
# Fetch a video
video = await client.get_video("https://www.porntrex.com/videos/12345/example-video/")
# Access metadata
print(video.title)
print(video.video_qualities) # list of available resolutions (e.g., ["360", "480", "720", "1080"])
# Download video using RAW downloader (direct MP4)
config = DownloadConfigRAW(quality="best", path="./downloads")
await video.download(configuration=config)
asyncio.run(main())
Configuration
Porntrex API uses eaf_base_api 4.x for networking. You can configure a proxy, timeouts, request attempts, limits, and headers via a custom BaseCore.
Please refer to the eaf_base_api Documentation for the complete reference on how to set up RuntimeConfig and BaseCore.
from base_api import BaseCore
from base_api.modules.config import RuntimeConfig
from porntrex_api import Client
my_config = RuntimeConfig()
my_config.proxy = "socks5://127.0.0.1:9050"
my_config.request_attempts = 4
core = BaseCore(configuration=my_config)
client = Client(core=core)
IteratorConfig, retry policy, and custom scrape errors
Iterator methods take one iterator_config object. Keep load_specific_sources=("html",) when replacing Porntrex's package defaults so full Video metadata is loaded.
from base_api import ErrorAction, ErrorMode, ResultOrder, RetryPolicy, ScrapeErrorContext
from base_api.modules.config import IteratorConfig
async def handle_scrape_error(context: ScrapeErrorContext) -> ErrorAction:
print(context.stage, context.url, context.error, context.attempt)
return ErrorAction.RETRY
retry = RetryPolicy(
max_attempts=3, base_delay=0.5, multiplier=2, max_delay=8, jitter=0.25
)
iterator_config = IteratorConfig(
max_page_concurrency=2,
max_item_concurrency=5,
order=ResultOrder.ORIGINAL,
load_specific_sources=("html",),
page_retry=retry,
item_retry=retry,
page_error_mode=ErrorMode.SKIP,
item_error_mode=ErrorMode.YIELD,
page_error_handler=handle_scrape_error,
item_error_handler=handle_scrape_error,
)
async for result in client.search("college", iterator_config=iterator_config):
print(result.unwrap().title if result.succeeded else result.error)
max_attempts includes the first attempt. page_error_handler and item_error_handler are routed independently. This example shares one callable because it intentionally applies the same retry decision to both stages; use separate callables when page and item policy differ.
Client
The main class to interact with the Porntrex scraper ecosystem.
from porntrex_api import Client
from base_api import BaseCore
client = Client()
client_custom = Client(core=BaseCore())
Constructor Parameters
- core BaseCore — Networking core instance (default:
BaseCore())
Methods
Fetch Video get_video()
Video object.Parameters
- url str — The Porntrex video page URL
- load_html bool — If
True(default), fetches and extracts metadata immediately
Returns
→ VideoFetch Model get_model()
Model object.Parameters
- url str — The Porntrex model profile page URL
- load_html bool — If
True(default), fetches and extracts metadata immediately
Returns
→ ModelFetch Channel get_channel()
Channel object.Parameters
- url str — The Porntrex channel page URL
- load_html bool — If
True(default), fetches and extracts metadata immediately
Returns
→ ChannelSearch Videos search()
Parameters
- query str — Search query string
- pages int — Number of search pages to parse (default:
2) - iterator_config IteratorConfig | None — Per-iterator concurrency, source loading, ordering, retry, error-mode, and custom-handler settings. The package default loads the
htmlsource.
Returns
→ AsyncGenerator[ScrapeResult[Video], None]Video
dataclass Inherits from BaseMedia. Represents a single video with details extracted from Porntrex's script variables.
Attributes
| Attribute | Type | Description |
|---|---|---|
url | str | The video page URL |
title | str | None | Video title |
video_id | str | None | Unique video key ID |
categories | list[str] | None | List of category labels |
tags | list[str] | None | List of tags |
license_code | str | None | License code metadata |
lrc | str | None | LRC string identifier |
rnd | str | None | Rnd hash value used in player config |
author | str | None | Username of the uploader |
publish_date | str | None | Uploader date description |
views | str | None | Number of views |
duration | str | None | Duration string (e.g. 12:34) |
description | str | None | Description of the video |
subscribers_count | str | None | Author's subscriber count |
thumbnail | str | None | Cover image thumbnail URL |
direct_download_urls | list[str] | None | Raw CDN download URLs ordered by resolution |
video_qualities | list[str] | None | Sorted list of available resolutions (e.g. ["360", "480", "720", "1080"]) |
Methods
Download Video download()
DownloadConfigRAW. Ordinary failures raise DownloadFailed with full diagnostic context and chained cause.Parameters
- configuration DownloadConfigRAW — RAW download options. See Downloading Options.
Returns
→ boolModel
dataclass Inherits from BaseMedia via ChannelModelHelper. Represents a model profile page.
Attributes
| Attribute | Type | Description |
|---|---|---|
url | str | Model profile page URL |
name | str | None | Name of the model |
information | dict | None | Key-value parameters extracted from the sidebar info container (e.g. age, views) |
thumbnail | str | None | Profile picture URL |
Methods
Get Model Videos videos()
Parameters
- pages int — Pages to parse (default:
2) - iterator_config IteratorConfig | None — Per-iterator concurrency, source loading, ordering, retry, error-mode, and custom-handler settings. The package default loads the
htmlsource.
Returns
→ AsyncGenerator[ScrapeResult[Video], None]Channel
dataclass Inherits from BaseMedia via ChannelModelHelper. Represents a publisher channel.
Attributes
| Attribute | Type | Description |
|---|---|---|
url | str | Channel page URL |
name | str | None | Name of the channel |
information | dict | None | Sidebar metadata key-value properties |
thumbnail | str | None | Channel cover profile picture URL |
Methods
Get Channel Videos videos()
Parameters
- pages int — Pages to parse (default:
2) - iterator_config IteratorConfig | None — Per-iterator concurrency, source loading, ordering, retry, error-mode, and custom-handler settings. The package default loads the
htmlsource.
Returns
→ AsyncGenerator[ScrapeResult[Video], None]Downloading Options
Porntrex media files are served directly as MP4 files. Configure downloads using DownloadConfigRAW:
from base_api import DownloadConfigRAW
config = DownloadConfigRAW(
quality="best", # "best", "half", "worst", or height int (e.g. 720)
path="./downloads", # Destination path
no_title=False, # If False, automatically appends title + ".mp4"
allow_multipart=True, # Enable multi-threaded range requests
max_workers=5 # Concurrent download segment threads
)
success = await video.download(configuration=config)
For a detailed breakdown of all available settings inside DownloadConfigRAW, please read the eaf_base_api Documentation.
Scraping Results
Iterators like client.search() and model.videos() return async generators that yield ScrapeResult containers:
async for result in client.search("college", pages=3):
if result.succeeded:
video = result.unwrap() # The Video object
print(video.title)
else:
print(f"{result.stage} failed: {result.error}")
ScrapeResult Attributes
| Attribute | Type | Description |
|---|---|---|
succeeded | bool | Whether the scraping task succeeded. |
unwrap() | Video | Returns the parsed video, or raises the stored error. |
item | Video | None | The parsed video when successful. |
error | ScrapeOperationError | None | The typed page or item failure. |
stage | ScrapeStage | The iterator stage: PAGE or ITEM. |
Error Handling
Source loaders translate request failures into exceptions from porntrex_api.modules.errors. Calls that load media expose ordinary loader failures through base_api.MediaLoadError (or MediaLoadErrors for several sources); inspect original_error/errors as shown. Operations outside media loading may still raise package or core exceptions directly.
Request and download failures are logged with the operation, target URL, and full original traceback. Translated exceptions retain the original error in __cause__. Download preparation failures (including metadata loading, quality selection, and output path setup) are also wrapped in DownloadFailed; inspect its cause when diagnosing a failure. The specific availability exceptions listed below remain supported. An explicit DownloadCancelled or asyncio.CancelledError propagates without being wrapped in DownloadFailed. Base downloader False and DownloadReport results remain supported; inspect the result as well as handling exceptions.
The common provider errors NotFound, NetworkError, BotDetection, ProxyError, UnknownNetworkError, and DownloadFailed are catchable through base_api.modules.errors. They derive from ScraperException, which now derives from BaseScraperError. Existing provider import paths remain valid.
See Logging & Cleanup for application logging setup.
| Exception | Trigger Cause |
|---|---|
NotFound | Server returned HTTP 404 (e.g. video/model deleted) |
NetworkError | Request failed due to a network error, exhausted request retries, or a non-404 HTTPStatusError |
BotDetection | Bot-protection challenge block detected |
ProxyError | Proxy configuration failed or proxy is down |
UnknownNetworkError | Unexpected network errors |
DownloadFailed | Download preparation or transfer failed; the video URL is included and __cause__ retains the original exception |
from base_api import MediaLoadError
from porntrex_api.modules.errors import NotFound, BotDetection
try:
video = await client.get_video(url)
except MediaLoadError as error:
if isinstance(error.original_error, NotFound):
print("This video does not exist!")
elif isinstance(error.original_error, BotDetection):
print("Scraper was blocked by anti-bot measures.")
else:
raise
Changelog
1.8 — 2026-09-15
541cd29/221d32b— Adopted shared request and download error handling withbase_api.modules.provider(requiringeaf-base-api>=4.2.0). Failed downloads now raiseDownloadFailedwith complete context. Added layout anchor validations to detect page structure changes. Implemented robust fallback selectors for video and channel/model metadata. Normalized protocol schemes for download URLs and validated quality availability. Added snippet-based unit tests for channel and video data extraction.
1.8 — 2026-08-11 d86ccad
- Added generic
ScrapeResult[Video]return annotations and thepy.typedmarker. - Changed unset iterator retry policies to resolve from the live
RuntimeConfig. - Updated the package version from 1.7 to 1.8.
IteratorConfig synchronization — 2026-08-08 aa51d6b
- Replaced the legacy per-call iterator arguments with
IteratorConfig. - Preserved the required
htmlsource loading for search, model, and channel results.
Core v4 migration — 2026-08-07 d731458
- Migrated to eaf-base-api 4.x with explicit request methods and source-aware media loading.
- Added bounded retries, structured errors, extractor validation, improved concurrency, and deterministic stream cleanup.
- Removed obsolete compatibility code and adopted the current
ScrapeResultmodel.
CLI Usage
The CLI entry point configures console logging at INFO level. Caught per-URL failures include the URL and full traceback; the default log format shows the logger, file, line, and function. Library applications should configure logging once at startup.
Porntrex API includes a command-line interface accessible via porntrex_api or python -m porntrex_api:
# Download a single video
porntrex_api --download "https://www.porntrex.com/video/12345/video-title" --quality best --output ./downloads --no-title False
# Or invoke via python -m
python -m porntrex_api --download "https://www.porntrex.com/video/12345/video-title" --quality best --output ./downloads --no-title False
# Download from a line-separated file of URLs
porntrex_api --file urls.txt --quality best --output ./downloads --no-title False
CLI Options
| Flag | Description |
|---|---|
--download URL | Video URL to download |
--file FILE | Text file with URLs (separated by newlines) |
--quality QUALITY | Video quality: best, half, worst |
--output DIR | Destination directory or output file path |
--no-title True/False | Skip auto-appending video title to output filename (default: False) |
Supported Platforms
| Platform | Architecture | Status |
|---|---|---|
| Windows 11 | x64 | ✅ Tested |
| macOS Sequoia | x86_64 / arm64 | ✅ Tested |
| Linux (Arch) | x86_64 | ✅ Tested |
| Android 16 | aarch64 | ✅ Tested |