Skip to content

Instantly share code, notes, and snippets.

@pavelgordon
Created April 30, 2020 15:43
Show Gist options
  • Save pavelgordon/c75db669ac7865f650f24acc3a093fad to your computer and use it in GitHub Desktop.
Save pavelgordon/c75db669ac7865f650f24acc3a093fad to your computer and use it in GitHub Desktop.
Downloads all posts from instagram in specific date range
import csv
from datetime import datetime
from instaloader import instaloader
def instaposts_streamer(query, date_from, date_to, filename):
cols = ['date', 'username', 'text', 'tags', 'permalink']
with open(filename, 'w') as f:
csv.writer(f, delimiter='|').writerow(cols)
L = instaloader.Instaloader()
posts = L.get_hashtag_posts(query)
SINCE = datetime.strptime(date_to, '%Y-%m-%d')
UNTIL = datetime.strptime(date_from, '%Y-%m-%d')
print("SINCE", SINCE)
print("UNTIL", UNTIL)
psts = []
for post in filter(lambda p: SINCE <= p.date <= UNTIL, posts):
if post.caption is None:
pst = [post.date, post.owner_username, post.caption, post.caption_hashtags,
'instagram.com/p/' + post.shortcode + '/']
else:
pst = [post.date, post.owner_username, post.caption.replace('\n', '\\n'), post.caption_hashtags,
'instagram.com/p/' + post.shortcode + '/']
print(post.date)
psts.append(pst)
with open(filename, 'a') as f:
csv.writer(f, delimiter='|').writerow(pst)
query = 'onlinebusiness'
date_from = '2020-04-20'
date_to = '2020-04-14'
filename = 'testinst2.csv'
res = instaposts_streamer(query, date_from, date_to, filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment