Python Module instaloader

Instaloader exposes its internally used methods as a Python module, making it a powerful and easy-to-use 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')

Besides Instaloader.get_hashtag_posts(), there is Instaloader.get_feed_posts() and Instaloader.get_profile_posts(). Also, Post instances can be created with Post.from_shortcode() and Post.from_mediaid().

Further, information about profiles can be easily obtained. For example, you may print a list of all followees and followers of a profile with:

# Print followees
print(PROFILE + " follows these profiles:")
for f in L.get_followees(PROFILE):
    print("\t%s\t%s" % (f['username'], f['full_name']))

# Print followers
print("Followers of " + PROFILE + ":")
for f in L.get_followers(PROFILE):
    print("\t%s\t%s" % (f['username'], f['full_name']))

Then, you may download all pictures of all followees with:

for f in L.get_followees(PROFILE):
    L.download_profile(f['username'])

Each Instagram profile has its own unique ID which stays unmodified even if a user changes his/her username. To get said ID, given the profile’s name, you may call:

L.get_id_by_username(PROFILE_NAME)

A reference of the many methods provided by the instaloader module is provided in the remainder of this document. Feel free to direct any issue or contribution to Instaloader on Github.

Instaloader (Main Class)

class Instaloader(sleep=True, quiet=False, user_agent=None, dirname_pattern=None, filename_pattern=None, download_videos=<Tristate.always: 2>, download_video_thumbnails=<Tristate.always: 2>, download_geotags=<Tristate.no_extra_query: 1>, save_captions=<Tristate.no_extra_query: 1>, download_comments=<Tristate.no_extra_query: 1>, save_metadata=<Tristate.never: 0>, max_connection_attempts=3)
is_logged_in

True, if this Instaloader instance is logged in.

Return type:bool
anonymous_copy()

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

error(msg, repeat_at_end=True)

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

Parameters:repeat_at_end – Set to false if the message should be printed, but not repeated at program termination.
get_json(url, params, session=None, _attempt=1)

JSON request to Instagram.

Parameters:
  • url (str) – URL, relative to www.instagram.com/
  • params (Dict[str, Any]) – GET parameters
  • 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_id, variables, referer=None)

Do a GraphQL Query.

Parameters:
  • query_id (int) – Query ID.
  • variables (Dict[str, Any]) – Variables for the Query.
  • referer (Optional[str]) – HTTP Referer, or None.
Return type:

Dict[str, Any]

Returns:

The server’s response dictionary.

get_username_by_id(profile_id)

To get the current username of a profile, given its unique ID, this function can be used.

Return type:str
get_id_by_username(profile)

Each Instagram profile has its own unique ID which stays unmodified even if a user changes his/her username. To get said ID, given the profile’s name, you may call this function.

Return type:int
graphql_node_list(query_id, query_variables, query_referer, edge_extractor)

Retrieve a list of GraphQL nodes.

Return type:Iterator[Dict[str, Any]]
get_followers(profile)

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

Parameters:profile (str) – Name of profile to lookup followers.
Return type:Iterator[Dict[str, Any]]
get_followees(profile)

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

Parameters:profile (str) – Name of profile to lookup followers.
Return type:Iterator[Dict[str, Any]]
download_pic(filename, url, mtime, filename_alt=None, filename_suffix=None)

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, post)

Saves metadata JSON file of a Post.

Return type:None
update_comments(filename, post, filename_alt=None)
Return type:None
save_caption(filename, mtime, caption, filename_alt=None)

Updates picture caption

Return type:None
save_location(filename, location_json, mtime)
Return type:None
download_profilepic(name, profile_metadata)

Downloads and saves profile pic.

Return type:None
save_session_to_file(filename=None)

Saves internally stored requests.Session object.

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(session)

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

Return type:None
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 (str) – 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.
Return type:Iterator[Dict[str, Any]]
download_stories(userids=None, fast_update=False, filename_target=':stories')

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[int]]) – List of user IDs to be processed in terms of downloading their stories
  • fast_update (bool) – If true, abort when first already-downloaded picture is encountered
  • filename_target (str) – Replacement for {target} in dirname_pattern and filename_pattern
Return type:

None

download_story(item, target, profile)

Download one user story.

Parameters:
  • item (Dict[str, Any]) – Story item, as in story[‘items’] for story in get_stories()
  • target (str) – Replacement for {target} in dirname_pattern and filename_pattern
  • profile (str) – Owner profile name
Return type:

bool

Returns:

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

get_feed_posts()

Get Posts of the user’s feed.

Return type:Iterator[Post]
download_feed_posts(max_count=None, fast_update=False, filter_func=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,
                           filter_func=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
  • filter_func (Optional[Callable[[Post], bool]]) – function(post), which returns True if given picture should be downloaded
Return type:

None

get_hashtag_posts(hashtag)

Get Posts associated with a #hashtag.

Return type:Iterator[Post]
download_hashtag(hashtag, max_count=None, filter_func=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
  • filter_func (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

check_profile_id(profile, profile_metadata=None)

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:
Return type:

Tuple[str, int]

Returns:

current profile name, profile id

get_profile_metadata(profile_name)

Retrieves a profile’s metadata, for use with e.g. get_profile_posts() and check_profile_id().

Return type:Dict[str, Any]
get_profile_posts(profile_metadata)

Retrieve all posts from a profile.

Return type:Iterator[Post]
download_profile(name, profile_pic=True, profile_pic_only=False, fast_update=False, download_stories=False, download_stories_only=False, filter_func=None)

Download one profile

Return type:None
interactive_login(username)

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

Raises:LoginRequiredException – when in quiet mode.
Return type:None
main(profilelist, username=None, password=None, sessionfile=None, max_count=None, profile_pic=True, profile_pic_only=False, fast_update=False, stories=False, stories_only=False, filter_str=None)

Download set of profiles, hashtags etc. and handle logging in and session files if desired.

Return type:None

Post Class

class Post(instaloader, node, profile=None, profile_id=None)

Structure containing information about an Instagram post.

Created by Instaloader methods get_profile_posts(), get_hashtag_posts(), get_feed_posts(). Posts are linked to an Instaloader instance which is used for error logging and obtaining of additional metadata, if required. This class unifies access to the properties associated with a post. It implements == and is hashable.

The properties defined here are accessible by the filter expressions specified with the --only-if parameter and exported into JSON files with --metadata-json.

LOGIN_REQUIRING_PROPERTIES = ['viewer_has_liked']
classmethod from_shortcode(instaloader, shortcode)

Create a post object from a given shortcode

classmethod from_mediaid(instaloader, mediaid)

Create a post object from a given mediaid

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_username

The Post’s lowercase owner name, or ‘UNKNOWN’.

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
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_edges()
Return type:List[Dict[str, Any]]
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]
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]
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

Return type:int
get_comments()

Iterate over all comments of the post.

Return type:Iterator[Dict[str, Any]]
get_location()

If the Post has a location, returns a dictionary with fields ‘lat’ and ‘lng’.

Return type:Optional[Dict[str, str]]
static json_encoder(obj)

Convert instance of Post to a JSON-serializable dictionary.

Return type:Dict[str, Any]

Miscellaneous Functions

shortcode_to_mediaid(code)
Return type:int
mediaid_to_shortcode(mediaid)
Return type:str
class Tristate

Bases: enum.Enum

Tri-state to encode whether we should save certain information, i.e. videos, captions, comments or geotags.

never
Do not save, even if the information is available without any additional request,
no_extra_query
Save if and only if available without doing additional queries,
always
Save (and query, if neccessary).
never = 0
no_extra_query = 1
always = 2

Exceptions

exception InstaloaderException

Base exception for this script.

Note:This exception should not be raised directly.
exception QueryReturnedNotFoundException

Bases: instaloader.InstaloaderException

exception ProfileNotExistsException

Bases: instaloader.InstaloaderException

exception ProfileHasNoPicsException

Bases: instaloader.InstaloaderException

exception PrivateProfileNotFollowedException

Bases: instaloader.InstaloaderException

exception LoginRequiredException

Bases: instaloader.InstaloaderException

exception InvalidArgumentException

Bases: instaloader.InstaloaderException

exception BadResponseException

Bases: instaloader.InstaloaderException

exception BadCredentialsException

Bases: instaloader.InstaloaderException

exception ConnectionException

Bases: instaloader.InstaloaderException

Next Section

Contributing to Instaloader