Other Options:
• PayPal
• Ko-Fi
For extended features, enterprise integrations, or custom commercial licensing, please contact support@echteralsfake.me.
Installation
Install from PyPI using pip:
pip install unofficial-api-for-spankbang
For TS→MP4 remuxing and metadata tagging support (recommended for HLS downloads with remux=True), ensure ffmpeg is installed on your system PATH (or set RuntimeConfig.ffmpeg_path).
eaf-base-api>=4.3.0 is installed automatically as a dependency.
Release 3.0.0 requires eaf-base-api>=4.3.0 from PyPI. A local base-API checkout is not required.
Quick Start
Every method in this API is asynchronous. You need to run your code inside an async function:
import asyncio
from spankbang_api import Client
async def main():
client = Client()
# Fetch a video
video = await client.get_video("https://spankbang.com/...")
# Access metadata
print(video.title)
print(video.length)
print(video.video_qualities)
# Download the video using HLS (default)
from base_api import DownloadConfigHLS
config = DownloadConfigHLS(quality="best", path="./downloads")
await video.download(configuration_hls=config, use_hls=True)
asyncio.run(main())
Configuration
The API uses eaf-base-api>=4.3.0. Configure its singular proxy, bounded request attempts, timeouts, and other runtime behavior through the BaseCore passed to Client.
Please refer to the eaf_base_api Documentation for the complete reference on how to set up RuntimeConfig and properly integrate it with this API.
The current client sets RuntimeConfig.http_version to "v3" before initializing its session and installs SpankBang's required Origin/Referer headers. Pass a core whose session has not already been initialized so the HTTP/3 setting takes effect.
from base_api import BaseCore
from base_api.modules.config import RuntimeConfig
from spankbang_api import Client
my_config = RuntimeConfig()
my_config.proxy = "socks5://127.0.0.1:9050"
my_config.request_attempts = 3
core = BaseCore(configuration=my_config)
client = Client(core=core)
Client
URL handling
This version requires eaf-base-api>=4.3.0. Profile pagination preserves filters and removes stale page query keys without adding duplicate slashes. Paginated listings start at page one and fetch one source page by default. Use pages="all" for the remaining listing or pages=2, start_page=3 to request pages three and four. Page counts and offsets must be positive integers. The only string accepted for pages is "all". Embed and play links normalize to video links. A configured Accept-Language header is preserved.
The Client class manages the network session, cookies, and HTTP headers to interact with SpankBang. It serves as the primary entry point to retrieve video details, explore profile channels/pornstars/creators, and run search queries.
from spankbang_api import Client
from base_api import BaseCore
client = Client()
# Or construct with custom core configuration
client_custom = Client(core=BaseCore())
Constructor Parameters
- core BaseCore — Networking core instance (default:
BaseCore(RuntimeConfig()))
Methods
Fetch Video get_video()
Video object. Parses Javascript variables containing HLS master playlists and direct MP4 resolutions.Parameters
- url str — The full SpankBang video URL
- load_html bool — If
True(default), fetches and parses the HTML page for metadata
Returns
→ VideoFetch Channel get_channel()
Channel object.Parameters
- url str — The full SpankBang channel URL
- load_html bool — If
True(default), parses the profile HTML for metadata
Returns
→ ChannelFetch Pornstar get_pornstar()
Pornstar object.Parameters
- url str — The full SpankBang pornstar URL
- load_html bool — If
True(default), parses the profile HTML for metadata
Returns
→ PornstarFetch Creator get_creator()
Creator object.Parameters
- url str — The full SpankBang creator URL
- load_html bool — If
True(default), parses the profile HTML
Returns
→ CreatorSearch Videos search()
Parameters
- query str — Search query keywords
- filter str | None — Filter order:
"trending","new","featured","popular" - quality str | None — Quality filter:
"hd"(720p),"fhd"(1080p),"uhd"(4k) - duration str | None — Duration limits:
"10"(10+ min),"20"(20+ min),"40"(40+ min) - date str | None — Upload date range:
"d"(day),"w"(week),"m"(month),"y"(year) - pages int | "all" — A positive page count or
"all"(default1). - start_page int — One-based starting page (default
1). - iterator_config IteratorConfig | None — Optional v4 concurrency, ordering, eager-source, retry, and error-handling policy. The package default eagerly loads
html.
Returns
→ AsyncGenerator[ScrapeResult[Video], None]Behavior and edge cases
Default listing concurrency is limited to two video loads and one page at a time. Search builds independent page URLs and encodes the query once. Bare video IDs and embed/play paths normalize to video pages; profile routing preserves regional hosts and supported path prefixes.
Video
dataclass Inherits from BaseMedia. Represents a single SpankBang video. Populated with metadata from parsed Javascript configurations (stream_data) on the page and standard HTML tags.
Attributes
| Attribute | Type | Description |
|---|---|---|
url | str | The video page URL |
title | str | None | Video title |
description | str | None | Description metadata content |
thumbnail | str | None | Video preview cover image URL |
tags | list | None | List of tags/categories |
author | str | None | Author / channel publisher name |
image | str | None | Author profile thumbnail / image alt text |
rating | str | None | Upvote percentage (e.g. 92%) |
length | str | None | Length in seconds |
m3u8_base_url | str | None | HLS master playlist URL |
direct_download_urls | list | None | CDN-resolved direct MP4 URLs |
video_qualities | list | None | Sorted list of available resolution heights (e.g. ["240", "320", "480", "720", "1080", "4k"]) |
| Scraper Iterator Fallback Attributes | ||
tag | str | None | Primary search tag associated with the item |
views | str | None | View count string from the listing card |
resolution | str | None | Maximum resolution badge from listing card |
video_source_url | str | None | Raw listing element fallbacks |
Methods
Download Video download()
use_hls parameter. Ordinary failures raise DownloadFailed with full diagnostic context and chained cause.Parameters
- configuration_hls DownloadConfigHLS | None — Config options for HLS segment downloads. Used if
use_hls=True. - configuration_raw DownloadConfigRAW | None — Config options for direct file downloads. Used if
use_hls=False. - use_hls bool — Download via HLS (default:
True). SetFalseto download via raw MP4 links.
Returns
→ bool | DownloadReportBehavior and edge cases
RAW quality selection accepts numeric values and supported labels such as hd, fhd, uhd and 4k, with the normal closest-tier fallback. Supplying only configuration_raw selects RAW mode automatically. Missing streams raise VideoUnavailable.
Pornstar / Channel / Creator
dataclass Inherits from PornstarHelper → BaseMedia. Under the hood, SpankBang profiles for Pornstar, Channel, and Creator share the same attributes and methods via a common base class.
Attributes
| Attribute | Type | Description |
|---|---|---|
url | str | The profile base URL |
name | str | None | Name of the pornstar, channel, or creator |
video_count | str | None | Total uploaded/featured videos |
views_count | str | None | Total profile views |
subscribers_count | str | None | Total subscriber count |
image | str | None | Profile avatar cover image URL |
Methods
Get Profile Videos videos()
Parameters
- pages int | "all" — A positive page count or
"all"(default1). - start_page int — One-based starting page (default
1). - iterator_config IteratorConfig | None — Optional v4 iterator policy. The default eagerly loads each video's
htmlsource.
Returns
→ AsyncGenerator[ScrapeResult[Video], None]Search & Filtering
Perform advanced searches on SpankBang by passing filter keywords to the `client.search()` generator:
# Search for popular 1080p videos uploaded this week
async for result in client.search(
query="college",
filter="popular",
quality="fhd", # 1080p resolution
date="w", # weekly
pages=3
):
if result.succeeded:
video = result.unwrap()
print(video.title, video.url)
Filter Parameters Map
Sort/Filter (filter)
| Value | Description |
|---|---|
"trending" | Trending videos (Default option) |
"new" | Most recent videos |
"featured" | Featured videos |
"popular" | Most popular videos |
Quality (quality)
| Value | Target Quality |
|---|---|
"hd" | High Definition (720p) |
"fhd" | Full High Definition (1080p) |
"uhd" | Ultra High Definition (4k resolution) |
Duration (duration)
| Value | Target Range |
|---|---|
"10" | Videos longer than 10 minutes |
"20" | Videos longer than 20 minutes |
"40" | Videos longer than 40 minutes |
Date Range (date)
| Value | Timeline |
|---|---|
"d" | Uploaded today |
"w" | Uploaded this week |
"m" | Uploaded this month |
"y" | Uploaded this year |
Downloading Options
SpankBang supports dual download configurations. Under the hood, the master playlist contains an HLS stream, but direct CDN links are also extracted if you prefer RAW MP4 chunked downloading.
HLS Download (Recommended)
HLS provides highly reliable stream downloads, slicing chunked `.ts` packages and remuxing them to `.mp4` via FFmpeg:
from base_api import DownloadConfigHLS
config = DownloadConfigHLS(
quality="best",
path="./downloads"
)
success = await video.download(configuration_hls=config, use_hls=True)
RAW CDN Download
RAW downloads request full files directly from SpankBang's media CDN servers, leveraging HTTP range requests to speed up the process across parallel workers:
from base_api import DownloadConfigRAW
config = DownloadConfigRAW(
quality="best", # "best", "half", "worst"
path="./downloads",
allow_multipart=True,
max_workers=5
)
success = await video.download(configuration_raw=config, use_hls=False)
Pagination & Iterators
All listings (such as client.search() and profile.videos()) yield typed ScrapeResult[Video] values. Use succeeded to branch safely or unwrap() to return the item and raise its terminal error on failure:
async for result in client.search("solo", pages=2):
if result.succeeded:
video = result.unwrap()
print(video.title)
else:
print(result.stage, result.url, result.error)
ScrapeResult Properties
| Attribute | Type | Description |
|---|---|---|
stage | ScrapeStage | Whether the result came from the page or item stage |
url | str | The video item page URL |
page_index | int | Zero-based source page index |
item_index | int | None | Zero-based item index, or None for a page failure |
attempts | int | Number of attempts used by the yielding stage |
item | Video | None | Populated video on success |
error | ScrapeOperationError | None | Typed terminal page or item error on failure |
succeeded | bool | True when error is None |
IteratorConfig, bounded retries, and custom handlers
A paginated stream raises or yields a failed page or item according to IteratorConfig. On these streams, ErrorMode.SKIP yields the error so callers can see that the scan is incomplete. Call result.unwrap() to get the item or raise the stored error. A retry policy's max_attempts includes the initial attempt, so this example makes at most three stage attempts per failed page or item. Each stage attempt may itself perform the request retries configured on BaseCore. Fully populated results require the html source.
Leave page_retry or item_retry as None to derive that stage's bounded policy from the active RuntimeConfig request-attempt and backoff settings; an explicit RetryPolicy overrides it per stage.
from base_api import ErrorAction, RetryPolicy, ScrapeErrorContext
from base_api.modules.config import IteratorConfig
async def handle_scrape_error(context: ScrapeErrorContext) -> ErrorAction:
if context.attempt < context.max_attempts:
return ErrorAction.RETRY
return ErrorAction.YIELD
retry = RetryPolicy(
max_attempts=3, base_delay=0.5, multiplier=2.0,
max_delay=4.0, jitter=0.2
)
iterator_config = IteratorConfig(
max_page_concurrency=2,
max_item_concurrency=8,
max_pending_items=16,
load_specific_sources=("html",),
page_retry=retry,
item_retry=retry,
page_error_handler=handle_scrape_error,
item_error_handler=handle_scrape_error,
)
async for result in client.search(
"solo", pages=2, iterator_config=iterator_config
):
if result.succeeded:
print(result.unwrap().title)
else:
print(result.stage, result.error)
ScrapeErrorContext supplies stage, url, error, attempt, max_attempts, page_index, and item_index. A handler returns ErrorAction.RETRY, RAISE, YIELD, or SKIP.
The core routes page-stage failures to page_error_handler and item-stage failures to item_error_handler. Assign the same callable to both fields only when both stages should use the same policy; otherwise configure either handler independently.
Error Handling
Source loaders translate request failures into exceptions from spankbang_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.
VideoIsProcessing derives from ScraperException and now has a non-empty default exception message. HLS and RAW download failures both retain their causes; a ResourceGone raised during downloading is translated to VideoUnavailable with the video URL.
| Exception | Trigger Cause |
|---|---|
NotFound | Server returned HTTP 404 (e.g. video 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 connection failed |
VideoIsProcessing | The video is still processing on SpankBang's servers |
VideoUnavailable | Video stream is unavailable from SpankBang |
DownloadFailed | Download preparation or transfer failed; the video URL is included and __cause__ retains the original exception |
from base_api import MediaLoadError
from spankbang_api.modules.errors import VideoIsProcessing, NotFound
try:
video = await client.get_video(url)
except MediaLoadError as error:
if isinstance(error.original_error, VideoIsProcessing):
print("This video is still processing!")
elif isinstance(error.original_error, NotFound):
print("Video no longer exists.")
else:
raise
Changelog
3.0.0 — 2026-11-15
- Use positive one-based offsets for search and profile videos. Follow the listing's own navigation for a full scan.
2.4.4 — 2026-10-27
- Build independent search page URLs and preserve special characters in search terms.
- Use conservative default listing concurrency and standard navigation headers.
- Keep each RAW download URL paired with its resolution and support numeric and named quality choices.
- Select RAW mode when only a RAW configuration is supplied, and add the --raw CLI flag.
- Normalize bare, embed and play links and handle regional profile paths and statistics.
- Improve thumbnail, duration and stream-data parsing across the supported page layouts.
GitHub release and distribution files · PyPI 2.4.4
Uses the published eaf-base-api>=4.2.5 dependency.
2.4.1 — 2026-09-15
35024f6/9ab9185— Adopted shared request and download error handling withbase_api.modules.provider(requiringeaf-base-api>=4.2.0). Failed downloads now raiseDownloadFailedwith complete context. Added 4K resolution support (sorted as 2160p) for video scraping and downloads. Upgraded scraper selectors across video, channel, creator, and pornstar pages with robust fallbacks anddata-testidattributes. Enhancedstream_dataregex parsing and added offline extraction unit tests.
2.4.1 — 2026-08-14
18a8f15/5871e80— Updated request headers and forced HTTP/3 for newly initialized client sessions to restore access after upstream 403 responses.
2.3 — 2026-08-11
809909a/71e71f6— Added the PEP 561py.typedmarker, left iterator retry policies unset so they resolve fromRuntimeConfig, and removed a temporary local package-source setting from the published configuration.
2.3 — 2026-08-08
e63c384— Consolidated profile and search iterator concurrency, ordering, source loading, retry, and error controls intoIteratorConfig.
2.3 migration — 2026-08-07
2f1c01d— Migrated to the eaf_base_api v4 request and scraping model:fetch_text()/request(), structured exceptions, source-aware media loading, typed scrape streams/results, bounded retries, and field-aware loading before downloads.
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.
SpankBang API includes a command-line interface accessible via spankbang_api or python -m spankbang_api:
# Download a single video
spankbang_api --download "https://spankbang.com/12345/video/sample" --quality best --output ./downloads --no-title False
# Or invoke via python -m
python -m spankbang_api --download "https://spankbang.com/12345/video/sample" --quality best --output ./downloads --no-title False
# Download from a line-separated file of URLs
spankbang_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) |
Behavior and edge cases
Use --raw for direct MP4 downloads:
spankbang_api --download URL --output downloads --quality 720 --raw
Supported Platforms
| Platform | Architecture | Status |
|---|---|---|
| Windows 11 | x64 | ✅ Tested |
| macOS Sequoia | x86_64 | ✅ Tested |
| Linux (Arch) | x86_64 | ✅ Tested |
| Android 16 | aarch64 | ✅ Tested |