Python Module instaloader

Instaloader exposes its internally used methods and structures as a Python module, making it a powerful and intuitive Python API for Instagram, allowing to further customize obtaining media and metadata.

Start with getting an instance of Instaloader:

import instaloader

# Get instance
L = instaloader.Instaloader()

# Optionally, login or load session
L.login(USER, PASSWORD)        # (login)
L.interactive_login(USER)      # (ask password on terminal)
L.load_session_from_file(USER) # (load session created w/
                               #  `instaloader -l USERNAME`)

instaloader provides the Post structure, which represents a picture, video or sidecar (set of multiple pictures/videos) posted in a user’s profile. Instaloader provides methods to iterate over Posts from a certain source:

for post in L.get_hashtag_posts('cat'):
    # post is an instance of instaloader.Post
    L.download_post(post, target='#cat')

Post instances can be created with:

With the Profile class, Instaloader also makes it easy to access metadata of a Profile. Profile instances can be created with:

A reference of the many methods provided by the instaloader module is provided in the remainder of this document.

For a list of real code examples using the Instaloader module for advanced tasks, see Advanced Instaloader Examples.

Instaloader (Main Class)

class Instaloader(sleep=True, quiet=False, user_agent=None, dirname_pattern=None, filename_pattern=None, download_pictures=True, download_videos=True, download_video_thumbnails=True, download_geotags=True, download_comments=True, save_metadata=True, compress_json=True, post_metadata_txt_pattern=None, storyitem_metadata_txt_pattern=None, max_connection_attempts=3, commit_mode=False)

Instaloader Class.

Parameters
context

The associated InstaloaderContext with low-level communication functions and logging.

anonymous_copy()

Yield an anonymous, otherwise equally-configured copy of an Instaloader instance; Then copy its error log.

close()

Close associated session objects and repeat error log.

download_pic(filename, url, mtime, filename_suffix=None, _attempt=1)

Downloads and saves picture with given url under given directory with given timestamp. Returns true, if file was actually downloaded, i.e. updated.

Return type

bool

save_metadata_json(filename, structure)

Saves metadata JSON file of a structure.

Return type

None

update_comments(filename, post)
Return type

None

save_caption(filename, mtime, caption)

Updates picture caption / Post metadata info

Return type

None

save_location(filename, location, mtime)

Save post location name and Google Maps link.

Return type

None

download_profilepic(profile, _attempt=1)

Downloads and saves profile pic.

Return type

None

save_session_to_file(filename=None)

Saves internally stored requests.Session object.

Parameters

filename (Optional[str]) – Filename, or None to use default filename.

Raises

LoginRequiredException – If called without being logged in.

Return type

None

load_session_from_file(username, filename=None)

Internally stores requests.Session object loaded from file.

If filename is None, the file with the default session path is loaded.

Raises

FileNotFoundError – If the file does not exist.

Return type

None

test_login()

Returns the Instagram username to which given requests.Session object belongs, or None.

Return type

Optional[str]

login(user, passwd)

Log in to instagram with given username and password and internally store session object.

Raises
Return type

None

two_factor_login(two_factor_code)

Second step of login if 2FA is enabled. Not meant to be used directly, use Instaloader.two_factor_login().

Raises

New in version 4.2.

Return type

None

format_filename(item, target=None)

Format filename of a Post or StoryItem according to filename-pattern parameter.

New in version 4.1.

download_post(post, target)

Download everything associated with one instagram post node, i.e. picture, caption and video.

Parameters
  • post (Post) – Post to download.

  • target (Union[str, Path]) – Target name, i.e. profile name, #hashtag, :feed; for filename.

Return type

bool

Returns

True if something was downloaded, False otherwise, i.e. file was already there

get_stories(userids=None)

Get available stories from followees or all stories of users whose ID are given. Does not mark stories as seen. To use this, one needs to be logged in

Parameters

userids (Optional[List[int]]) – List of user IDs to be processed in terms of downloading their stories, or None.

Raises

LoginRequiredException – If called without being logged in.

Return type

Iterator[Story]

download_stories(userids=None, fast_update=False, filename_target=':stories', storyitem_filter=None)

Download available stories from user followees or all stories of users whose ID are given. Does not mark stories as seen. To use this, one needs to be logged in

Parameters
  • userids (Optional[List[Union[int, Profile]]]) – List of user IDs or Profiles to be processed in terms of downloading their stories

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

  • filename_target (Optional[str]) – Replacement for {target} in dirname_pattern and filename_pattern or None if profile name should be used instead

  • storyitem_filter (Optional[Callable[[StoryItem], bool]]) – function(storyitem), which returns True if given StoryItem should be downloaded

Raises

LoginRequiredException – If called without being logged in.

Return type

None

download_storyitem(item, target)

Download one user story.

Parameters
  • item (StoryItem) – Story item, as in story[‘items’] for story in get_stories()

  • target (Union[str, Path]) – Replacement for {target} in dirname_pattern and filename_pattern

Return type

bool

Returns

True if something was downloaded, False otherwise, i.e. file was already there

get_highlights(user)

Get all highlights from a user. To use this, one needs to be logged in.

New in version 4.1.

Parameters

user (Union[int, Profile]) – ID or Profile of the user whose highlights should get fetched.

Raises

LoginRequiredException – If called without being logged in.

Return type

Iterator[Highlight]

download_highlights(user, fast_update=False, filename_target=None, storyitem_filter=None)

Download available highlights from a user whose ID is given. To use this, one needs to be logged in.

New in version 4.1.

Parameters
  • user (Union[int, Profile]) – ID or Profile of the user whose highlights should get downloaded.

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

  • filename_target (Optional[str]) – Replacement for {target} in dirname_pattern and filename_pattern or None if profile name and the highlights’ titles should be used instead

  • storyitem_filter (Optional[Callable[[StoryItem], bool]]) – function(storyitem), which returns True if given StoryItem should be downloaded

Raises

LoginRequiredException – If called without being logged in.

Return type

None

get_feed_posts()

Get Posts of the user’s feed.

Return type

Iterator[Post]

Returns

Iterator over Posts of the user’s feed.

Raises

LoginRequiredException – If called without being logged in.

download_feed_posts(max_count=None, fast_update=False, post_filter=None)

Download pictures from the user’s feed.

Example to download up to the 20 pics the user last liked:

loader = Instaloader()
loader.load_session_from_file('USER')
loader.download_feed_posts(max_count=20, fast_update=True,
                           post_filter=lambda post: post.viewer_has_liked)
Parameters
  • max_count (Optional[int]) – Maximum count of pictures to download

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

  • post_filter (Optional[Callable[[Post], bool]]) – function(post), which returns True if given picture should be downloaded

Raises

LoginRequiredException – If called without being logged in.

Return type

None

download_saved_posts(max_count=None, fast_update=False, post_filter=None)

Download user’s saved pictures.

Parameters
  • max_count (Optional[int]) – Maximum count of pictures to download

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

  • post_filter (Optional[Callable[[Post], bool]]) – function(post), which returns True if given picture should be downloaded

Raises

LoginRequiredException – If called without being logged in.

Return type

None

get_location_posts(location)

Get Posts which are listed by Instagram for a given Location.

Return type

Iterator[Post]

Returns

Iterator over Posts of a location’s posts

Raises

LoginRequiredException – If called without being logged in.

New in version 4.2.

Changed in version 4.2.9: Require being logged in (as required by Instagram)

download_location(location, max_count=None, post_filter=None, fast_update=False)

Download pictures of one location.

To download the last 30 pictures with location 362629379, do:

loader = Instaloader()
loader.download_location(362629379, max_count=30)
Parameters
  • location (str) – Location to download, as Instagram numerical ID

  • max_count (Optional[int]) – Maximum count of pictures to download

  • post_filter (Optional[Callable[[Post], bool]]) – function(post), which returns True if given picture should be downloaded

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

Raises

LoginRequiredException – If called without being logged in.

New in version 4.2.

Changed in version 4.2.9: Require being logged in (as required by Instagram)

Return type

None

get_explore_posts()

Get Posts which are worthy of exploring suggested by Instagram.

Return type

Iterator[Post]

Returns

Iterator over Posts of the user’s suggested posts.

Raises

LoginRequiredException – If called without being logged in.

get_hashtag_posts(hashtag)

Get Posts associated with a #hashtag.

Return type

Iterator[Post]

download_hashtag(hashtag, max_count=None, post_filter=None, fast_update=False)

Download pictures of one hashtag.

To download the last 30 pictures with hashtag #cat, do:

loader = Instaloader()
loader.download_hashtag('cat', max_count=30)
Parameters
  • hashtag (str) – Hashtag to download, without leading ‘#’

  • max_count (Optional[int]) – Maximum count of pictures to download

  • post_filter (Optional[Callable[[Post], bool]]) – function(post), which returns True if given picture should be downloaded

  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered

Return type

None

download_tagged(profile, fast_update=False, target=None, post_filter=None)

Download all posts where a profile is tagged.

New in version 4.1.

Return type

None

save_profile_id(profile)

Store ID of profile locally.

New in version 4.0.6.

check_profile_id(profile_name)

Consult locally stored ID of profile with given name, check whether ID matches and whether name has changed and return current name of the profile, and store ID of profile.

Parameters

profile_name (str) – Profile name

Return type

Profile

Returns

Instance of current profile

download_profiles(profiles, profile_pic=True, posts=True, tagged=False, highlights=False, stories=False, fast_update=False, post_filter=None, storyitem_filter=None, raise_errors=False)

High-level method to download set of profiles.

Parameters

New in version 4.1.

download_profile(profile_name, profile_pic=True, profile_pic_only=False, fast_update=False, download_stories=False, download_stories_only=False, download_tagged=False, download_tagged_only=False, post_filter=None, storyitem_filter=None)

Download one profile

Deprecated since version 4.1: Use Instaloader.download_profiles().

Return type

None

check_if_committed(filename)

Checks to see if the current post has been committed.

A post is considered committed if its json metadata file exists and is not malformed.

New in version 4.2.

Return type

bool

interactive_login(username)

Logs in and internally stores session, asking user for password interactively.

Raises
Return type

None

Instagram Structures

Posts

class Post(context, node, owner_profile=None)

Structure containing information about an Instagram post.

Created by methods Profile.get_posts(), Instaloader.get_hashtag_posts(), Instaloader.get_feed_posts() and Profile.get_saved_posts(), which return iterators of Posts:

L = Instaloader()
for post in L.get_hashtag_posts(HASHTAG):
    L.download_post(post, target='#'+HASHTAG)

Might also be created with:

post = Post.from_shortcode(L.context, SHORTCODE)

This class unifies access to the properties associated with a post. It implements == and is hashable.

Parameters
classmethod from_shortcode(context, shortcode)

Create a post object from a given shortcode

classmethod from_mediaid(context, mediaid)

Create a post object from a given mediaid

static shortcode_to_mediaid(code)
Return type

int

static mediaid_to_shortcode(mediaid)
Return type

str

shortcode

Media shortcode. URL of the post is instagram.com/p/<shortcode>/.

Return type

str

mediaid

The mediaid is a decimal representation of the media shortcode.

Return type

int

owner_profile

Profile instance of the Post’s owner.

Return type

Profile

owner_username

The Post’s lowercase owner name.

Return type

str

owner_id

The ID of the Post’s owner.

Return type

int

date_local

Timestamp when the post was created (local time zone).

Return type

datetime

date_utc

Timestamp when the post was created (UTC).

Return type

datetime

date

Synonym to date_utc

Return type

datetime

profile

Synonym to owner_username

Return type

str

url

URL of the picture / video thumbnail of the post

Return type

str

typename

Type of post, GraphImage, GraphVideo or GraphSidecar

Return type

str

get_sidecar_nodes()

Sidecar nodes of a Post with typename==GraphSidecar.

Return type

Iterator[PostSidecarNode]

caption

Caption.

Return type

Optional[str]

caption_hashtags

List of all lowercased hashtags (without preceeding #) that occur in the Post’s caption.

Return type

List[str]

caption_mentions

List of all lowercased profiles that are mentioned in the Post’s caption, without preceeding @.

Return type

List[str]

pcaption

Printable caption, useful as a format specifier for –filename-pattern.

New in version 4.2.6.

Return type

str

tagged_users

List of all lowercased users that are tagged in the Post.

Return type

List[str]

is_video

True if the Post is a video.

Return type

bool

video_url

URL of the video, or None.

Return type

Optional[str]

video_view_count

View count of the video, or None.

New in version 4.2.6.

Return type

Optional[int]

video_duration

Duration of the video in seconds, or None.

New in version 4.2.6.

Return type

Optional[float]

viewer_has_liked

Whether the viewer has liked the post, or None if not logged in.

Return type

Optional[bool]

likes

Likes count

Return type

int

comments

Comment count including answers

Return type

int

get_comments()

Iterate over all comments of the post.

Each comment is represented by a PostComment namedtuple with fields text (string), created_at (datetime), id (int), owner (Profile) and answers (Iterator[PostCommentAnswer]) if available.

Return type

Iterator[PostComment]

get_likes()

Iterate over all likes of the post. A Profile instance of each likee is yielded.

Return type

Iterator[Profile]

location

If the Post has a location, returns PostLocation namedtuple with fields ‘id’, ‘lat’ and ‘lng’ and ‘name’.

Changed in version 4.2.9: Require being logged in (as required by Instagram), return None if not logged-in.

Return type

Optional[PostLocation]

Additionally, the following trivial structures are defined:

class PostSidecarNode

Item of a Sidecar Post.

display_url

URL of image or video thumbnail.

is_video

Whether this node is a video.

video_url

URL of video or None.

class PostComment(id, created_at_utc, text, owner, likes_count, answers)
answers

Iterator which yields all PostCommentAnswers for the comment.

created_at_utc

datetime when comment was created (UTC).

id

ID number of comment.

likes_count

Number of likes on comment.

owner

Owner Profile of the comment.

text

Comment text.

class PostCommentAnswer(id, created_at_utc, text, owner, likes_count)
created_at_utc

datetime when comment was created (UTC).

id

ID number of comment.

likes_count

Number of likes on comment.

owner

Owner Profile of the comment.

text

Comment text.

class PostLocation(id, name, slug, has_public_page, lat, lng)
has_public_page

Whether location has a public page.

id

ID number of location.

lat

Latitude (float).

lng

Longitude (float).

name

Location name.

slug

URL friendly variant of location name.

User Stories

class Story(context, node)

Structure representing a user story with its associated items.

Provides methods for accessing story properties, as well as Story.get_items() to request associated StoryItem nodes. Stories are returned by Instaloader.get_stories().

With a logged-in Instaloader instance L, you may download all your visible user stories with:

for story in L.get_stories():
    # story is a Story object
    for item in story.get_items():
        # item is a StoryItem object
        L.download_storyitem(item, ':stories')

This class implements == and is hashable.

Parameters
unique_id

This ID only equals amongst Story instances which have the same owner and the same set of StoryItem. For all other Story instances this ID is different.

Return type

Union[str, int]

last_seen_local

Timestamp when the story has last been watched or None (local time zone).

Return type

Optional[datetime]

last_seen_utc

Timestamp when the story has last been watched or None (UTC).

Return type

Optional[datetime]

latest_media_local

Timestamp when the last item of the story was created (local time zone).

Return type

datetime

latest_media_utc

Timestamp when the last item of the story was created (UTC).

Return type

datetime

itemcount

Count of items associated with the Story instance.

Return type

int

owner_profile

Profile instance of the story owner.

Return type

Profile

owner_username

The story owner’s lowercase username.

Return type

str

owner_id

The story owner’s ID.

Return type

int

get_items()

Retrieve all items from a story.

Return type

Iterator[StoryItem]

class StoryItem(context, node, owner_profile=None)

Structure containing information about a user story item i.e. image or video.

Created by method Story.get_items(). This class implements == and is hashable.

Parameters
mediaid

The mediaid is a decimal representation of the media shortcode.

Return type

int

shortcode

Convert mediaid to a shortcode-like string, allowing {shortcode} to be used with --filename-pattern.

Return type

str

owner_profile

Profile instance of the story item’s owner.

Return type

Profile

owner_username

The StoryItem owner’s lowercase name.

Return type

str

owner_id

The ID of the StoryItem owner.

Return type

int

date_local

Timestamp when the StoryItem was created (local time zone).

Return type

datetime

date_utc

Timestamp when the StoryItem was created (UTC).

Return type

datetime

date

Synonym to date_utc

Return type

datetime

profile

Synonym to owner_username

Return type

str

expiring_local

Timestamp when the StoryItem will get unavailable (local time zone).

Return type

datetime

expiring_utc

Timestamp when the StoryItem will get unavailable (UTC).

Return type

datetime

url

URL of the picture / video thumbnail of the StoryItem

Return type

str

typename

Type of post, GraphStoryImage or GraphStoryVideo

Return type

str

is_video

True if the StoryItem is a video.

Return type

bool

video_url

URL of the video, or None.

Return type

Optional[str]

Highlights

class Highlight(context, node, owner=None)

Structure representing a user’s highlight with its associated story items.

Provides methods for accessing highlight properties, as well as Highlight.get_items() to request associated StoryItem nodes. Highlights are returned by Instaloader.get_highlights().

With a logged-in Instaloader instance L, you may download all highlights of a Profile instance USER with:

for highlight in L.get_highlights(USER):
    # highlight is a Highlight object
    for item in highlight.get_items():
        # item is a StoryItem object
        L.download_storyitem(item, '{}/{}'.format(highlight.owner_username, highlight.title))

This class implements == and is hashable.

Parameters

Bases: Story

New in version 4.1.

unique_id

A unique ID identifying this set of highlights.

Return type

int

owner_profile

Profile instance of the highlights’ owner.

Return type

Profile

title

The title of these highlights.

Return type

str

cover_url

URL of the highlights’ cover.

Return type

str

cover_cropped_url

URL of the cropped version of the cover.

Return type

str

itemcount

Count of items associated with the Highlight instance.

Return type

int

get_items()

Retrieve all associated highlight items.

Return type

Iterator[StoryItem]

last_seen_local

Timestamp when the story has last been watched or None (local time zone).

Return type

Optional[datetime]

last_seen_utc

Timestamp when the story has last been watched or None (UTC).

Return type

Optional[datetime]

latest_media_local

Timestamp when the last item of the story was created (local time zone).

Return type

datetime

latest_media_utc

Timestamp when the last item of the story was created (UTC).

Return type

datetime

owner_id

The story owner’s ID.

Return type

int

owner_username

The story owner’s lowercase username.

Return type

str

Profiles

class Profile(context, node)

An Instagram Profile.

Provides methods for accessing profile properties, as well as Profile.get_posts() and for own profile Profile.get_saved_posts().

Get instances with Post.owner_profile(), StoryItem.owner_profile(), Profile.get_followees(), Profile.get_followers() or:

L = Instaloader()
profile = Profile.from_username(L.context, USERNAME)

Provides Profile.get_posts() and for own profile Profile.get_saved_posts() to iterate over associated Post objects:

for post in profile.get_posts():
    L.download_post(post, target=profile.username)

Profile.get_followees() and Profile.get_followers():

print("{} follows these profiles:".format(profile.username))
for followee in profile.get_followees():
    print(followee.username)

Also, this class implements == and is hashable.

classmethod from_username(context, username)

Create a Profile instance from a given username, raise exception if it does not exist.

See also Instaloader.check_profile_id().

Parameters
Raises

ProfileNotExistsException

classmethod from_id(context, profile_id)

Create a Profile instance from a given userid. If possible, use Profile.from_username() or constructor directly rather than this method, since it requires more requests.

Parameters
Raises

ProfileNotExistsException

userid

User ID

Return type

int

username

Profile Name

Return type

str

is_private
Return type

bool

followed_by_viewer
Return type

bool

mediacount
Return type

int

followers
Return type

int

followees
Return type

int

external_url
Return type

Optional[str]

biography
Return type

str

blocked_by_viewer
Return type

bool

follows_viewer
Return type

bool

full_name
Return type

str

has_blocked_viewer
Return type

bool

has_highlight_reels

Deprecated since version 4.0.6: Always returns True since issue #153.

Before broken, this indicated whether the Profile had available stories.

Return type

bool

has_public_story
Return type

bool

has_viewable_story

Deprecated since version 4.0.6.

Some stories are private. This property determines if the Profile has at least one story which can be viewed using the associated InstaloaderContext, i.e. the viewer has privileges to view it.

Return type

bool

has_requested_viewer
Return type

bool

is_verified
Return type

bool

requested_by_viewer
Return type

bool

profile_pic_url

Return URL of profile picture. If logged in, the HD version is returned, otherwise a lower-quality version.

New in version 4.0.3.

Changed in version 4.2.1: Require being logged in for HD version (as required by Instagram).

Return type

str

get_profile_pic_url()

Deprecated since version 4.0.3.

Use profile_pic_url.

Return type

str

get_posts()

Retrieve all posts from a profile.

Return type

Iterator[Post]

get_saved_posts()

Get Posts that are marked as saved by the user.

Return type

Iterator[Post]

get_tagged_posts()

Retrieve all posts where a profile is tagged.

New in version 4.0.7.

Return type

Iterator[Post]

get_followers()

Retrieve list of followers of given profile. To use this, one needs to be logged in and private profiles has to be followed.

Return type

Iterator[Profile]

get_followees()

Retrieve list of followees (followings) of given profile. To use this, one needs to be logged in and private profiles has to be followed.

Return type

Iterator[Profile]

Loading and Saving

Post, StoryItem and Profile can be saved and loaded to/from JSON files.

load_structure_from_file(context, filename)

Loads a Post, Profile or StoryItem from a ‘.json’ or ‘.json.xz’ file that has been saved by save_structure_to_file().

Parameters
Return type

Union[Post, Profile, StoryItem]

save_structure_to_file(structure, filename)

Saves a Post, Profile or StoryItem to a ‘.json’ or ‘.json.xz’ file such that it can later be loaded by load_structure_from_file().

If the specified filename ends in ‘.xz’, the file will be LZMA compressed. Otherwise, a pretty-printed JSON file will be created.

Parameters
Return type

None

Exceptions

exception InstaloaderException

Base exception for this script.

Note

This exception should not be raised directly.

exception ConnectionException

Bases: instaloader.exceptions.InstaloaderException

exception QueryReturnedBadRequestException

Bases: instaloader.exceptions.InstaloaderException

exception QueryReturnedNotFoundException

Bases: instaloader.exceptions.InstaloaderException

exception QueryReturnedForbiddenException

Bases: instaloader.exceptions.InstaloaderException

exception ProfileNotExistsException

Bases: instaloader.exceptions.InstaloaderException

exception ProfileHasNoPicsException

Bases: instaloader.exceptions.InstaloaderException

Deprecated since version 4.2.2: Not raised anymore.

exception PrivateProfileNotFollowedException

Bases: instaloader.exceptions.InstaloaderException

exception LoginRequiredException

Bases: instaloader.exceptions.InstaloaderException

exception TwoFactorAuthRequiredException

Bases: instaloader.exceptions.InstaloaderException

New in version 4.2.

exception InvalidArgumentException

Bases: instaloader.exceptions.InstaloaderException

exception BadResponseException

Bases: instaloader.exceptions.InstaloaderException

exception BadCredentialsException

Bases: instaloader.exceptions.InstaloaderException

exception PostChangedException

Bases: instaloader.exceptions.InstaloaderException

New in version 4.2.2.

exception TooManyRequestsException

Bases: instaloader.exceptions.ConnectionException

InstaloaderContext (Low-level functions)

class InstaloaderContext(sleep=True, quiet=False, user_agent=None, max_connection_attempts=3)

Class providing methods for (error) logging and low-level communication with Instagram.

It is not thought to be instantiated directly, rather Instaloader instances maintain a context object.

For logging, it provides log(), error(), error_catcher().

It provides low-level communication routines get_json(), graphql_query(), graphql_node_list(), get_and_write_raw() and implements mechanisms for rate controlling and error handling.

Further, it provides methods for logging in and general session handles, which are used by that routines in class Instaloader.

anonymous_copy()
is_logged_in

True, if this Instaloader instance is logged in.

Return type

bool

log(*msg, sep='', end='\n', flush=False)

Log a message to stdout that can be suppressed with –quiet.

error(msg, repeat_at_end=True)

Log a non-fatal error message to stderr, which is repeated at program termination.

Parameters
  • msg – Message to be printed.

  • repeat_at_end – Set to false if the message should be printed, but not repeated at program termination.

close()

Print error log and close session

error_catcher(extra_info=None)

Context manager to catch, print and record InstaloaderExceptions.

Parameters

extra_info (Optional[str]) – String to prefix error message with.

get_anonymous_session()

Returns our default anonymous requests.Session object.

Return type

Session

save_session_to_file(sessionfile)

Not meant to be used directly, use Instaloader.save_session_to_file().

load_session_from_file(username, sessionfile)

Not meant to be used directly, use Instaloader.load_session_from_file().

test_login()

Not meant to be used directly, use Instaloader.test_login().

Return type

Optional[str]

login(user, passwd)

Not meant to be used directly, use Instaloader.login().

Raises
two_factor_login(two_factor_code)

Second step of login if 2FA is enabled. Not meant to be used directly, use Instaloader.two_factor_login().

Raises

New in version 4.2.

do_sleep()

Sleep a short time if self.sleep is set. Called before each request to instagram.com.

get_json(path, params, host='www.instagram.com', session=None, _attempt=1)

JSON request to Instagram.

Parameters
  • path (str) – URL, relative to the given domain which defaults to www.instagram.com/

  • params (Dict[str, Any]) – GET parameters

  • host (str) – Domain part of the URL from where to download the requested JSON; defaults to www.instagram.com

  • session (Optional[Session]) – Session to use, or None to use self.session

Return type

Dict[str, Any]

Returns

Decoded response dictionary

Raises
graphql_query(query_hash, variables, referer=None, rhx_gis=None)

Do a GraphQL Query.

Parameters
  • query_hash (str) – Query identifying hash.

  • variables (Dict[str, Any]) – Variables for the Query.

  • referer (Optional[str]) – HTTP Referer, or None.

  • rhx_gis (Optional[str]) – ‘rhx_gis’ variable as somewhere returned by Instagram, needed to ‘sign’ request

Return type

Dict[str, Any]

Returns

The server’s response dictionary.

graphql_node_list(query_hash, query_variables, query_referer, edge_extractor, rhx_gis=None, first_data=None)

Retrieve a list of GraphQL nodes.

Return type

Iterator[Dict[str, Any]]

get_iphone_json(path, params)

JSON request to i.instagram.com.

Parameters
  • path (str) – URL, relative to i.instagram.com/

  • params (Dict[str, Any]) – GET parameters

Return type

Dict[str, Any]

Returns

Decoded response dictionary

Raises

New in version 4.2.1.

write_raw(resp, filename)

Write raw response data into a file.

New in version 4.2.1.

Return type

None

get_raw(url, _attempt=1)

Downloads a file anonymously.

Raises

New in version 4.2.1.

Return type

Response

get_and_write_raw(url, filename)

Downloads and writes anonymously-requested raw data into a file.

Raises
Return type

None

root_rhx_gis

rhx_gis string returned in the / query.

Return type

Optional[str]

Next Section

Advanced Instaloader Examples

Table of Contents