Skip to content

Repository files navigation

Instagram Posts Scraper API by Scrapier

Instagram Posts Scraper for Python

Scrape an Instagram account's posts to JSON, with captions, engagement counts, carousel items and media URLs. Built on the Scrapier API: one HTTPS request, no headless browser to run, no parser to maintain.

tests Python 3.9+ Get a free API key

Quickstart · Fields · CLI · FAQ

Quickstart

  1. Get an API key from the Scrapier dashboard. No credit card needed to start.

  2. Install:

    pip install git+https://github.com/get-scrapier/Instagram-Posts-Scraper
  3. Run:

from scrapier_instagram_profile_posts import InstagramProfilePosts

client = InstagramProfilePosts(api_key="sk_live_...")   # or set SCRAPIER_API_KEY

for post in client.iter_profile_posts("mrbeast", max_items=60):
    # like_count and likes_count are the same number
    print(post["shortcode"], post["like_count"],
          post["comment_count"], post["caption"][:60])

The same code is in examples/quickstart.py.

Use cases

  • Engagement analysis
  • Content research
  • Competitor tracking
  • Influencer vetting

What it does

Walks an account's posts, twelve a page, with the caption, the engagement counts, the carousel children and the media URLs.

The richest of the Instagram post endpoints, and the one with the most redundant field names -- read the quirks before writing a parser.

Wraps the instagram-profile-posts endpoint, 12 rows a page.

Three ways to call

# 1. A list. For scripts and one-liners.
rows = client.profile_posts(username, max_items=100)

# 2. A generator. Streams, so you can stop early and stop paying.
for row in client.iter_profile_posts(username):
    handle(row)

# 3. A page at a time. You hold the cursor, so you can resume later.
page = client.profile_posts_page(username)
save(page.items)
while page.has_more:
    page = client.profile_posts_page(cursor=page.next_cursor)
    save(page.items)

A Page carries the rows plus the envelope:

page.items          # the rows
page.next_cursor    # opaque string, or None
page.has_more       # bool
page.raw_responses  # upstream payloads, when raw_data=True
page.data           # the whole envelope
len(page)           # number of rows

Fields you actually get back

Observed on live responses, not copied from a schema.

Field Notes
id, pk, shortcode, post_url, url identity, five ways
caption, accessibility_caption the text
like_count, likes_count the same number under two names -- see the quirks
comment_count, comments_count likewise
view_count, views_count likewise
comments, latest_comments embedded comments
is_video, has_audio, video_duration, video_links, video_versions video
image, images, image_links, display_url, thumbnail stills, also under several names
is_carousel, carousel_media, carousel_media_count carousels
is_pinned whether the account pinned it
hashtags, mentions, usertags tagging
owner, user, account_username, account_verified, account_profile_picture the author, also duplicated
coauthor_producers collaborators
clips_metadata, product_type, type what kind of media
date, posted, taken_at_timestamp when, three ways
dimensions width and height
from_url, keyword, crawled_at, scraped_at request metadata

Options

Argument What it does
pinned_mode What to do with pinned posts: include them in place, skip them, or return only the pinned ones. One of: include, skip, only.

Quirks worth knowing

Nearly every count appears twice under different names. Measured on a live response: like_count and likes_count, comment_count and comments_count, view_count and views_count, plus image / images / image_links and date / posted / taken_at_timestamp. They are the upstream payload's own duplication, passed through untouched. Pick one spelling and stay with it.

pinned_mode="only" is a cheap way to read just what an account chose to feature, and "skip" keeps a chronological walk from being interrupted by pinned posts.

Rows are snake_case here, while scrapier-instagram-profile-reels returns camelCase for the same concepts.

Controlling what you spend

Each page is a billable request, so bound a broad walk:

client.profile_posts(username, max_items=200)   # stop after 200 rows
client.profile_posts(username, max_pages=5)     # stop after 5 requests

max_items truncates mid-page rather than buying another page to fill a quota. Checking your balance is free:

print(client.credits())
print(client.account())

Async

AsyncInstagramProfilePosts exposes every method InstagramProfilePosts does, with identical arguments.

import asyncio
from scrapier_instagram_profile_posts import AsyncInstagramProfilePosts

async def main():
    async with AsyncInstagramProfilePosts() as client:
        rows = await client.profile_posts(username)

asyncio.run(main())

Bulk jobs

For hundreds of inputs, submit one background job instead of paging:

job = client.bulk([...], max_items=1000)   # up to 10,000 per input
print(job.job_id, job.status)

rows = job.wait(timeout=1800, poll_interval=5)

Reattach from another process with client.job(job_id), then read job.data.

Submits are deduplicated server-side on the request parameters, so an identical submit returns the job the first one created — including when that job failed. Vary a parameter to force a fresh attempt.

Errors

Everything derives from ScrapierError, so one except can catch the lot while you still get to be specific when it matters.

from scrapier_instagram_profile_posts import InsufficientCreditsError, RateLimitError, ScrapierError

try:
    rows = client.profile_posts(username)
except InsufficientCreditsError as exc:
    print(f"out of credits: {exc.balance} left, {exc.required} needed")
except RateLimitError as exc:
    print(f"slow down for {exc.retry_after}s")
except ScrapierError as exc:
    print(f"something else: {exc}")
Exception When
ConfigurationError no API key, or a reserved parameter was passed
TransportError the request never got a response
BadRequestError 400 — bad input
AuthenticationError 401 — bad or missing key
InsufficientCreditsError 402 with a balance — carries .balance and .required
NotFoundError 404
RateLimitError 429 — carries .retry_after
ScrapeTimeoutError 504 — the scrape itself ran out of time
ServiceUnavailableError 503
ServerError 5xx
JobFailedError a bulk job finished in failed — carries .errors
APIError the base for anything with a status code

429, 503, 5xx and transport failures are retried automatically with jittered backoff that honours Retry-After. 400, 401, 404 and a 402 about your balance are not — retrying those only wastes time.

Command line

export SCRAPIER_API_KEY=sk_live_...

scrapier-instagram-profile-posts <username> --max-items 50 --jsonl

JSON on stdout and nothing else, so it pipes. Global flags (--api-key, --base-url, --timeout, --jsonl, --indent) work anywhere on the line. Exit codes: 0 success, 2 usage or configuration, 3 API error.

Client reference

InstagramProfilePosts(
    api_key=None,        # falls back to $SCRAPIER_API_KEY
    base_url=None,       # falls back to $SCRAPIER_BASE_URL, then the default
    timeout=240.0,
    max_retries=3,       # for 429/503/5xx and transport failures
    http_client=None,    # bring your own httpx.Client
)

The key is sent in the X-API-Key header only — never in a URL or a request body, so it will not end up in a proxy log.

Every call also accepts method="GET" if you would rather the parameters went in the query string, use_proxy=True to route the scrape through Scrapier's proxy pool, and raw_data=True to get the upstream payloads instead of parsed rows.

Python 3.9+. The only dependency is httpx. Ships py.typed.

FAQ

Is this Instagram Posts Scraper free?

The client code is MIT-licensed. It needs a Scrapier API key, and requests are billed in credits; failed requests are not billed. See pricing. You can start without a credit card.

Do I need proxies or a headless browser?

No. The scrape runs on Scrapier's servers and returns JSON.

How do I scrape in bulk?

Use bulk jobs: submit many inputs as one background job, then job.wait().

Can an AI agent use this?

Yes. See AGENTS.md, or connect the Scrapier MCP server.

More from Scrapier

180+ endpoints across 35+ platforms: browse them all.

Support

Open an issue or read the docs.

License

MIT. See LICENSE.