You run requests.get("https://www.instagram.com/natgeo/"), print the response and go looking for the follower count you can see in your browser. It is not there in any form you can use. If you want to scrape Instagram with Python, this is where most attempts stall, and the reason has nothing to do with your code. The profile is put together by JavaScript after the page loads, and Instagram's anti-bot stack decides who gets served at all.
The fix is a fetch that renders the page in a real browser and goes out through a proxy. The shortest way to get one from Python is a single GET to the Ujeebu Scrape API with url set to the profile and recipe=instagram. It returns a small JSON object with the account name, the follower count and Instagram's own summary line. The rest of this post shows that response as it actually comes back, then builds on it: a loop over many profiles, numeric columns parsed out of display strings like "267M", and a CSV at the end.
Why requests alone falls short on Instagram
Two things work against you, and adding headers fixes neither.
The first is rendering. requests downloads HTML and stops. It does not run JavaScript, and the numbers you want are drawn by JavaScript. You can copy a browser's user agent exactly and still miss them.
The second is access. Instagram runs an anti-bot stack, and a script fetching profiles from a cloud server is the traffic it is built to filter. The do-it-yourself answer is a headless browser, a pool of proxies you rotate and replace as they get flagged, and selectors you rewrite each time Instagram moves its markup. All of that can be built. The maintenance is what wears people down: the scraper breaks on Instagram's schedule, not yours.
Before you build anything, check the official route. Instagram has an API, documented in the Instagram Graph API docs. See whether it covers your use case before scraping. The rest of this post is about public profile pages.
Scrape Instagram with Python: one call, JSON back
Setup is short. Install the library with pip install requests, then put your API key in an environment variable so it stays out of your code:
export UJEEBU_API_KEY="YOUR_API_KEY"
If you do not have a key yet, the free trial gives you 5,000 credits for 21 days with no credit card, or 30 days if you sign up with a verified work email.
Here is the call in curl, with nothing in the way:
curl -X GET 'https://api.ujeebu.com/scrape?url=https://www.instagram.com/natgeo/&recipe=instagram' \
-H "ApiKey: YOUR_API_KEY"
Here is what the API returned when we ran this exact request (it cost 5 credits), trimmed for length:
{
"result": {
"account_name": "natgeo",
"description": "267M Followers, 196 Following, 32K Posts - See Instagram photos and videos from National Geographic (@natgeo)",
"followers": "267M",
"image": "https://scontent-lga3-3.cdninstagram.com/v/t51.82787-19/683576066_18653628823019133_9051036240972105113_n.jpg?stp=dst-jpg_s150x150_tt6&_nc_c...",
"title": "National Geographic (@natgeo) • Instagram photos and videos",
"url": "https://www.instagram.com/natgeo/"
},
"success": true
}
We ran exactly that call while writing this post. It cost 5 credits and returned this:
{
"result": {
"account_name": "natgeo",
"description": "267M Followers, 196 Following, 32K Posts - See Instagram photos and videos from National Geographic (@natgeo)",
"followers": "267M",
"image": "https://scontent-lga3-3.cdninstagram.com/v/t51.82787-19/683576066_18653628823019133_9051036240972105113_n.jpg?stp=dst-jpg_s150x150_tt6&_nc_c...",
"title": "National Geographic (@natgeo) • Instagram photos and videos",
"url": "https://www.instagram.com/natgeo/"
},
"success": true
}
Everything useful sits under result, next to a top-level success flag, so the first thing your code checks is that flag. Inside result, account_name is the handle and url is the canonical profile URL. title is the page title, which carries the display name ("National Geographic") ahead of the handle. image is the profile picture on Instagram's CDN.
The two fields to read carefully are followers and description. followers is a display string, "267M", not an integer, so you cannot sort or sum it until you parse it. description is Instagram's summary line, not the bio, and it is the only place the following and post counts appear: 196 Following, 32K Posts. Those are display values too, and Instagram rounds them, so 32K posts is a rounded figure, not an exact count.
That is the whole response. It is a profile summary, one profile per call, not a feed of posts or Instagram listings JSON. For tracking accounts over time (audience size, posting volume, which handles in a list are growing) it is usually what you need. If you need more of the page than that, the trade-offs section below covers the other route.
The recipe parameter does the work. A recipe is a set of settings we have tested for one site plus the extraction that turns the rendered page into named fields. For Instagram it means js=true (render in headless Chrome), device=mobile (load the page as a phone would), wait_for=15000 (give the page time to finish filling in) and scroll_down=true, all on the rotating proxy. You pass none of these yourself: recipe=instagram applies them.
The same call from Python:
import os
import requests
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
resp = requests.get(
"https://api.ujeebu.com/scrape",
params={"url": "https://www.instagram.com/natgeo/", "recipe": "instagram"},
headers={"ApiKey": API_KEY},
timeout=120, # the page renders and waits, so give the client room
)
data = resp.json() if resp.ok else {}
if data.get("success"):
profile = data["result"]
print(profile["account_name"], profile["followers"])
print(profile["description"])
else:
print(resp.status_code, resp.text[:300])
The timeout=120 is deliberate. A recipe call renders, waits and scrolls, so it takes seconds, not milliseconds. If you carry over a short client timeout from some other script, requests gives up while the API is still working and you never see the answer. The API's own timeout parameter defaults to 60 seconds, so keep your client timeout comfortably above that.
Try it yourself
Run this on your own pages
Get a free API key and make your first call in minutes. 5,000 free credits for 21 days, no card.
From one profile to a list of profiles
One profile is a demo. In practice you have fifty or five hundred handles, so the job becomes a loop, and a good loop does a few things beyond calling the API in sequence.
It normalises input first. Handles arrive as @nasa, NASA and https://www.instagram.com/nasa, and each spelling would be a separate request for the same page. Stripping the @, lower-casing, building the URL yourself and then deduplicating avoids paying twice for one profile.
It goes at a steady pace. A short sleep between calls costs little on a few hundred profiles and keeps the run predictable. Plans do allow parallel requests (20 concurrent on Starter, up to 300 on Business), but a sequential loop is far easier to debug. Parallelise when a run is too slow, not before.
It sets failures aside instead of hammering them. A profile that fails goes on a list and gets one more try at the end of the run. The reliability section explains why that costs you nothing.
It measures what the run cost. GET https://api.ujeebu.com/account returns your used and balance figures, so calling it once before the loop and once after tells you exactly what the run consumed. Keep it to those two calls: the endpoint allows 10 calls per minute.
Saving Instagram profiles to CSV with Python
The response is nearly flat, which makes the CSV easy. The interesting work is turning display strings into numbers you can analyse.
The script keeps the six fields from result as they are, so you always have the original text, and adds parsed columns next to them. followers_num turns "267M" into a plain integer you can sort and sum. following_num and posts_num come out of the description line with a regular expression. display_name is the part of title before (@. All parsed counts are approximate, because Instagram rounds what it displays: parsing 32K gives you the rounded figure, not the true post count.
The parsing is defensive on purpose. description is text Instagram writes, so if a profile's line does not match the pattern, those cells stay empty instead of crashing the run. The same goes for files: bios and display names are full of emoji and non-Latin scripts, so the file is opened with encoding="utf-8" and newline="", and csv.DictWriter gets restval="" so a missing value becomes an empty cell instead of an exception halfway through a long run.
Here is the whole pipeline:
import csv
import os
import re
import time
from datetime import datetime, timezone
import requests
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
HEADERS = {"ApiKey": API_KEY}
HANDLES = ["natgeo", "@NASA", "nasa", "https://www.instagram.com/natgeo"]
COLUMNS = ["account_name", "display_name", "followers", "followers_num",
"following_num", "posts_num", "description", "title", "image",
"url", "fetched_at"]
COUNTS = re.compile(r"([\d.,]+[KMB]?) Followers, ([\d.,]+[KMB]?) Following, "
r"([\d.,]+[KMB]?) Posts")
SCALE = {"K": 1_000, "M": 1_000_000, "B": 1_000_000_000}
def to_url(handle):
h = handle.strip().rstrip("/").split("/")[-1].lstrip("@").lower()
return f"https://www.instagram.com/{h}/"
def to_number(text):
"""'267M' -> 267000000. Approximate: Instagram rounds display counts."""
try:
text = (text or "").replace(",", "").strip()
if text and text[-1].upper() in SCALE:
return int(float(text[:-1]) * SCALE[text[-1].upper()])
return int(float(text))
except ValueError:
return ""
def used_credits():
acct = requests.get("https://api.ujeebu.com/account",
headers=HEADERS, timeout=30).json()
return acct["used"]
def fetch_profile(url):
try:
resp = requests.get(
"https://api.ujeebu.com/scrape",
params={"url": url, "recipe": "instagram"},
headers=HEADERS,
timeout=120,
)
except requests.RequestException as exc:
print(url, "network error:", exc)
return None
data = resp.json() if resp.ok else {}
if not data.get("success"):
print(url, resp.status_code, resp.text[:200])
return None
return data["result"]
def to_row(profile):
row = {k: profile.get(k, "") for k in
("account_name", "followers", "description", "title", "image", "url")}
row["display_name"] = (profile.get("title") or "").split(" (@")[0]
row["followers_num"] = to_number(profile.get("followers"))
match = COUNTS.search(profile.get("description") or "")
if match:
row["following_num"] = to_number(match.group(2))
row["posts_num"] = to_number(match.group(3))
row["fetched_at"] = datetime.now(timezone.utc).isoformat()
return row
urls = list(dict.fromkeys(to_url(h) for h in HANDLES))
rows, failed = [], []
used_before = used_credits()
for attempt in (1, 2): # the second pass retries only what failed
todo, failed = (urls if attempt == 1 else failed), []
for url in todo:
profile = fetch_profile(url)
if profile is None:
failed.append(url)
else:
rows.append(to_row(profile))
time.sleep(2)
with open("instagram_profiles.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=COLUMNS, restval="")
writer.writeheader()
writer.writerows(rows)
print(f"{len(rows)} profiles saved, still failing: {failed}")
print("credits used in this run:", used_credits() - used_before)
The four handles in that list collapse to two URLs after normalising, so the run makes two calls, not four. Open the CSV and the natgeo row has 267M in followers and the same value as a full integer in followers_num, which is the column you sort on.
How reliable the Instagram recipe is, and what a failure costs
Saying a scraper works is easy, so here is a measurement instead. In the 7 days to late November 2026, our health checks ran the Instagram recipe 28 times and it passed 96.4% of them. Treat that as a recent reading, not a promise. It also tells you how to write your client: failures are rare but real, so the script should expect the occasional one and move on without drama. That is the job of the second pass.
Billing is what makes that pattern cheap. Failed requests are not billed, and that includes bot-check pages returned instead of the profile: a bot-check page that comes back in place of the profile is detected and treated as a failed request. You get an error, not a charge for a useless page, and a retry that fails again also costs nothing. The script retries at the end of the run rather than immediately, which keeps the retries from piling onto a profile that just failed.
The trade-off of a recipe is that you get its fields and only its fields. Most of the time that is what you want: named JSON from a health-checked extraction instead of selectors you maintain yourself. If you need more of the page, the Scrape API can return the rendered HTML of the same profile and you parse it yourself, accepting that the parsing is now yours to keep alive. Our BeautifulSoup tutorial covers that route, and the Instagram scraping page has more on the setup.
What scraping Instagram profiles costs at scale
Each profile costs 5 credits, the rate for a page rendered with JavaScript on the rotating proxy. On paid plans that works out to $0.82 per 1,000 JavaScript-rendered requests on Starter and $0.33 per 1,000 on Business, with the larger plans in between. The used difference the script prints at the end is the number to trust for your own runs.
Two optional parameters matter as you scale. proxy_country sets the country the page is fetched from; geo-targeting is available on paid plans. Most public profiles look the same from anywhere, so reach for it only once you have confirmed the page differs by country. proxy_session keeps the same exit IP for every request from your account that shares a session value, while a new value gets a different IP and no value keeps the usual rotation. For a list of unrelated profiles, leave it off and let rotation do its job.
Batch jobs for larger runs are coming soon. If you would rather receive a maintained Instagram data feed than run a script yourself, our custom scraping service builds and runs the scraper for you.
Where to go from here
Run the single-profile snippet first and look at the JSON with your own eyes, then point the full script at your list of handles. The Instagram recipe page documents the recipe, the recipes catalogue shows which other sites have one ready, and the Craigslist tutorial walks through the same JSON-to-CSV pattern on a different site.
When you know how many profiles you need to read each month, compare the plans on the pricing page.
FAQ
Is scraping Instagram with Python legal?
It depends on your jurisdiction, the data you collect and what you do with it. Read Instagram's terms, collect only what you need, and get legal advice before running anything commercial or large in scale.
Why does Instagram block Python requests without a scraping API?
Two reasons. The profile is built by JavaScript, which requests does not run, so the data you want is not in what you download. And Instagram's anti-bot stack filters automated traffic, so even a headless browser on a server needs proxies that hold up. A scraping API handles both the rendering and the access in one call.
What fields does the Ujeebu Instagram recipe return?
A success flag and a result object with account_name, followers, description, title, image and url. Counts come back as display strings such as "267M", and the following and post counts only appear inside description, so parse them if you need numbers.
How many credits does one Instagram profile cost, and are failures charged?
A successful profile read costs 5 credits. Failed requests are not billed, including bot-check pages returned instead of the profile, so retrying a profile that failed costs nothing unless the retry succeeds.
Can I scrape multiple Instagram profiles in one script?
Yes. Normalise and dedupe the handles, call the API once per profile with a short sleep between calls, retry the failures once at the end, and write the rows to CSV. The full script above does all of that and reports the credits the run used.
Try it yourself
Run this on your own pages
Get a free API key and make your first call in minutes. 5,000 free credits for 21 days, no card.