class TestIgramscraper(unittest.TestCase): @classmethod def setUpClass(self): cwd = os.getcwd() session_folder = cwd + os.path.sep + 'sessions' + os.path.sep if username == None or password == None: self.instagram = Instagram() else: self.instagram = Instagram.with_credentials( username, password, session_folder) self.instagram.login() if user_agent != None: #set user agent pass @classmethod def tearDownClass(self): pass def test_get_account_by_username(self): account = self.instagram.get_account('kevin') self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier) def test_get_account_by_id(self): account = self.instagram.get_account_by_id(3) self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier)
def ig_scraper(): instagram = Instagram() instagram.with_credentials('ICmemes666', 'devandcaitlyn') instagram.login() account = instagram.get_account('ICmemes666') # # Available fields # print('Account info:') # print('Id: ', account.identifier) # print('Username: '******'Full name: ', account.full_name) # print('Biography: ', account.biography) # print('Profile pic url: ', account.get_profile_pic_url_hd()) # print('External Url: ', account.external_url) # print('Number of published posts: ', account.media_count) # print('Number of followers: ', account.followed_by_count) # print('Number of follows: ', account.follows_count) # print('Is private: ', account.is_private) # print('Is verified: ', account.is_verified) # # print(instagram.get_account('ICmemes666')) medias = instagram.get_medias_by_user_id(account.identifier) return render_template('ig_scraper.html', medias=medias, title="Instagram")
def insta_usr(): instagram = Instagram() # authentication supported instagram.with_credentials(username, password) instagram.login() account = instagram.get_account(usr) print(f"\t{account}") server = DiscordWebhooks(webhook_url) try: server.set_image(url=account.profile_pic_url) server.add_field(name="UserName : "******"Hacking is not a trick. It's an state of mind :)") server.set_author(name="HackersBrain Instagram Analyser Bot", url="http://gauravraj.gq/", icon_url="https://source.unsplash.com/35x35/?man") server.add_field(name="Full Name : ", value=account.full_name) server.add_field(name="Bio : ", value=account.biography) server.add_field(name="No. of Posts : ", value=account.media_count) server.add_field(name="No. of Followers : ", value=account.followed_by_count) server.add_field(name="No. of Follows : ", value=account.follows_count) server.add_field(name="Is Private : ", value=account.is_private) server.add_field(name="Is Verified : ", value=account.is_verified) server.send() print(Fore.GREEN + "\t Message Sent Successfully...\n" + Style.RESET_ALL) except KeyboardInterrupt as key_err: print(" Exiting Program... \tProject by : HackersBrain\n") except Exception as err: print(f"\n {err}\n Exiting Program... \tProject by : HackersBrain\n")
class Scraper(): def __init__(self, username, password): self.username = username self.password = password self.scraper = Instagram() self.scraper.with_credentials(username, password) self.scraper.login() def target_by_username(self, target_name, tweet_count=None): rows = [[ 'username', 'full name', 'biography', 'prive', 'verfied', 'picture' ]] target = self.scraper.get_account(target_name) if not tweet_count: tweet_count = target.follows_count followers = self.scraper.get_followers(target.identifier, tweet_count, 100, delayed=True) for item in followers['accounts']: rows.append([ item.username, item.full_name, item.biography, item.is_private, item.is_verified, item.profile_pic_url ]) return rows
def start(): while True: try: print("iter") instagram = Instagram() instagram.with_credentials(insta_username, insta_password) instagram.login(force=False,two_step_verificator=True) sleep(2) # Delay to mimic user followers = [] account = instagram.get_account(username) sleep(1) curr_time = datetime.datetime.now(timezone('Asia/Kolkata')) curr_time = curr_time.strftime("%b %d, %Y - %H:%M:%S") followers = instagram.get_followers(account.identifier, FOLLOWER_LIMIT, 100, delayed=True) # Get 150 followers of 'kevin', 100 a time with random delay between requests # print(followers) current_followers = [] for follower in followers['accounts']: current_followers.append(follower.username) del followers if not path.exists("follower_list.txt"): f = open("follower_list.txt","w") f.write(str(current_followers)) f.close() else: f = open("follower_list.txt","r+") old_followers = f.read() f.close() old_followers = ast.literal_eval(old_followers) unfollowers = check_unfollowers(current_followers,old_followers) followers = check_followers(current_followers,old_followers) follower_change = len(current_followers)-len(old_followers) follow_count = len(followers) unfollow_count = len(unfollowers) discord_webhook.send_msg(username,follower_change,followers,unfollowers,follow_count,unfollow_count,curr_time,discord_webhook_url) f = open("follower_list.txt","w") f.write(str(current_followers)) f.close() except KeyboardInterrupt: print("Exiting...") sys.exit(0) except Exception as e: print(e) sleep(MINS_TO_SLEEP*60)
def getigStats(username): instagram = Instagram() data = { 'account': {}} account = instagram.get_account(username) data['account']['id'] = account.identifier data['account']['username'] = account.username data['account']['Full name'] = account.full_name data['account']['Biography'] = account.biography data['account']['Profile pic url'] = account.get_profile_picture_url() data['account']['Number of published posts'] = account.media_count data['account']['Number of followers'] = account.followed_by_count data['account']['Number of follows'] = account.follows_count today = date.today().strftime("%Y-%m-%d") firebse = firebase.FirebaseApplication('https://covidai-1dd78.firebaseio.com/', None) previous = firebse.get('https://covidai-1dd78.firebaseio.com/covidai-1dd78/followcount/', '') keys = previous.keys() print(keys) newEntry = 0 for key in keys: if(username == key): newEntry = 1 for sna in previous[key].keys(): stamp = sna print(stamp) Dataurl = 'https://covidai-1dd78.firebaseio.com/covidai-1dd78/followcount/'+username+'/' flag = 0 previous = firebse.get(Dataurl+stamp, '') print(previous) da = previous[-1].get(today, '') print(da) if(da): diff = account.followed_by_count - previous[-1][today] data['account']['diff'] = diff flag = 1 print(diff) if(diff != 0): previous[-1][today] = account.followed_by_count snap = str(len(previous) - 1) print('diff not') result = firebse.put(Dataurl+stamp, snap, {today:previous[-1][today]}) break if(flag == 0): previous.append({ today: account.followed_by_count }) result = firebse.put(Dataurl, stamp, previous) diff = account.followed_by_count - previous[-1][today] print('update') data['account']['diff'] = diff break if(newEntry == 0): print('new entry') Dataurl = 'https://covidai-1dd78.firebaseio.com/covidai-1dd78/followcount/'+username firebse.post(Dataurl, [{today: account.followed_by_count}]) return data
class TestIgramscraper(unittest.TestCase): @classmethod def setUpClass(self): cwd = os.getcwd() session_folder = cwd + os.path.sep + 'sessions' + os.path.sep if username == None or password == None: self.instagram = Instagram() else: self.instagram = Instagram.with_credentials( username, password, session_folder) self.instagram.login() if user_agent != None: #TODO set user agent pass @classmethod def tearDownClass(self): pass def test_get_account_by_username(self): account = self.instagram.get_account('kevin') self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier) def test_get_account_by_id(self): account = self.instagram.get_account_by_id(3) self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier) def test_get_medias(self): medias = self.instagram.get_medias('kevin', 80) self.assertEqual(80, len(medias)) def test_get_hundred_medias(self): medias = self.instagram.get_medias('kevin', 100) self.assertEqual(100, len(medias)) def test_get_medias_by_tag(self): medias = self.instagram.get_medias_by_tag('youneverknow', 20) self.assertEqual(20, len(medias)) def test_get_medias_by_code(self): media = self.instagram.get_medias_by_code('BHaRdodBouH') self.assertEqual('kevin', media.owner.username) def test_get_media_by_url(self): media = self.instagram.get_media_by_url( 'https://www.instagram.com/p/BHaRdodBouH') self.assertEqual('kevin', media.owner.username)
def __init__(this, user1, user2): this.user1 = user1 this.user2 = user2 instagram = Instagram() instagram.with_credentials('*****@*****.**', 'Yakapus0123') instagram.login() sleep(3) user1FollowersList = [] user2FollowersList = [] this.mutualFollowers = [] account1 = instagram.get_account(this.user1) sleep(2) account2 = instagram.get_account(this.user2) sleep(2) user1Followers = instagram.get_followers(account1.identifier, account1.followed_by_count, 100, delayed=True) user2Followers = instagram.get_followers(account2.identifier, account1.followed_by_count, 100, delayed=True) print(user1Followers) for f in user1Followers['accounts']: user1FollowersList.append(f.username) for f in user2Followers['accounts']: user2FollowersList.append(f.username) this.mutualFollowers = set(user1FollowersList) & set( user2FollowersList)
def accountChecker(self , username) : instagram = Instagram() instagram.set_proxies({ 'http': 'http://*****:*****@167.71.74.160:7015', 'https': 'http://*****:*****@167.71.74.160:7015' }) try : account = instagram.get_account(username) if(account.media_count > 5 and account.followed_by_count > 50 and account.followed_by_count <35000) : return True return False except : return True
def login(): username = input("Type your username: "******"Type your password: "******"Type the number of people you are following: ")) instagram = Instagram() instagram.with_credentials(username, password, './cache/') try: instagram.login(force=False,two_step_verificator=True) except Exception: print('Incorrect credentials. Relaunch and try again.') return False sleep(2) # Delay to mimic user account = instagram.get_account(username) print(bcolors.OKGREEN + 'Connected to account ' + bcolors.BOLD + account.full_name + ' @' + account.username + bcolors.ENDC) print("Export date: ", today.strftime("%d/%m/%Y")) return True
def get_handles(): instagram = Instagram() instagram.with_credentials('USERNAME', 'PASSWORD') instagram.login() data = pd.read_csv( 'C:\\Users\\sligh\\PycharmProjects\\test\\test-sheet.csv', usecols=['handle'], skip_blank_lines=True) dataframe = pd.DataFrame(data=data) for row in dataframe.itertuples(index=False, name=None): handle = str(row) translation_table = dict.fromkeys(map(ord, '(\'),'), None) handle = handle.translate(translation_table) print(handle) account = instagram.get_account(handle) print(handle + ': ', account.identifier) time.sleep(10)
def instagram_intelligence_report(): iguser = request.form['iguser'] instagram = Instagram() instagram.with_credentials('testingOSINT', 'osintpass123') instagram.login() account = instagram.get_account(iguser) username = account.username profile_name = account.full_name profile_bio = account.biography profile_pic_url = account.get_profile_picture_url() profile_externalurl = account.external_url profile_posts = account.media_count profile_follower = account.followed_by_count profile_following = account.follows_count profile_is_private = account.is_private profile_is_verified = account.is_verified return render_template("instagram_intelligence.html", iguser=iguser, username=username, profile_name=profile_name, profile_follower=profile_follower, profile_following=profile_following, profile_posts=profile_posts, profile_bio=profile_bio, profile_pic_url=profile_pic_url, profile_externalurl=profile_externalurl, profile_is_private=profile_is_private, profile_is_verified=profile_is_verified)
def search_account_by_username(data): data_escucha = escucha.objects.get(id=data['id_escucha']) data_campana = campana_publicitaria.objects.get(id=data['id_campana']) data_red_social = red_social.objects.get(id=data['id_red']) escucha_type = data['escucha_type'] instagram = Instagram() try: account = instagram.get_account(data['nombre_usuario']) except: logger.error( "*********************************************************************************" ) logger.error( "No se ha encontrado datos de cuenta en la tarea de obtener cuenta por tag" ) logger.error( "********************************************************************************" ) else: data_red_cuentas = cuentas_empresa.objects.filter( username=account.username, data_red_escucha=data_escucha, data_red_campana=data_campana).values() if not data_red_cuentas: new_account = cuentas_empresa( identifier=account.identifier, username=account.username, followers_count=account.followed_by_count, following_count=account.follows_count, post_count=account.media_count, listed_count=account.media_count, fullname=account.full_name, profile_pic_url=account.profile_pic_url, is_competition=escucha_type, data_red_escucha=data_escucha, data_red_campana=data_campana, data_red_social=data_red_social) new_account.save() logger.error('Task get instagram accounts has finished succesfully')
def getUser(username): instagram = Instagram() symbol = '@' account = instagram.get_account(username) sleep(1) try: if(account.business_email): return account.business_email name = account.full_name if(symbol in name): name = re.findall('\S+@\S+', name) if(name == []): return return name else: bio = account.biography if(symbol in bio): bio = re.findall('\S+@\S+', bio) if(bio == []): return return bio except: return
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 22:04:33 2021 @author: she84 """ from igramscraper.instagram import Instagram import csv proxies = {'192.168.43.249'} instagram = Instagram() instagram.set_proxies(proxies) account = instagram.get_account('jjr_yaya') # # Available fields # print('Account info:') # print('Id: ', account.identifier) # print('Username: '******'Full name: ', account.full_name) # print('Biography: ', account.biography) # print('Profile pic url: ', account.get_profile_picture_url()) # print('External Url: ', account.external_url) # print('Number of published posts: ', account.media_count) # print('Number of followers: ', account.followed_by_count) # print('Number of follows: ', account.follows_count) # print('Is private: ', account.is_private) # print('Is verified: ', account.is_verified)
while True: try: instagram.login() except Exception as e: file = open('cred.txt', "r+") deleteContent(file) file.close() raise e targetUsername = input("Enter Target Username: "******"Number Of Posts: ") # For getting information about account you don't need to auth: print('please wait this may take a few minutes...') account = instagram.get_account(targetUsername) posts = instagram.get_medias(targetUsername, int(numOfPost)) followerCount = account.followed_by_count def engagementRatio(post): return float(post.likes_count / followerCount) def printPost(posts): book = xlsxwriter.Workbook(f"{targetUsername}.xlsx") infoSheet = book.add_worksheet("Info") infoSheet.set_column(0, 1, 20) infoSheet.write(0, 0, "Username") infoSheet.write(0, 1, account.username)
from igramscraper.instagram import Instagram # pylint: disable=no-name-in-module from time import sleep instagram = Instagram() instagram.with_credentials('pietro.sonnini00', 'F&#yig4x0j5D') instagram.login(force=False, two_step_verificator=True) sleep(20) # Delay to mimic user username = '******' followings = [] account = instagram.get_account(username) sleep(1) followings = instagram.get_following( account.identifier, 100, 50, delayed=True ) # Get 150 followers of 'username', 100 a time with random delay between requests for following in followings['accounts']: if following.is_private == False: print(following.username)
class TestIgramscraper(unittest.TestCase): @classmethod def setUpClass(self): cwd = os.getcwd() session_folder = cwd + os.path.sep + 'sessions' + os.path.sep if username == None or password == None: self.instagram = Instagram() else: self.instagram = Instagram() self.instagram.with_credentials(username, password, session_folder) self.instagram.login() if user_agent != None: #TODO set user agent pass @classmethod def tearDownClass(self): pass def test_get_account_by_username(self): account = self.instagram.get_account('kevin') self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier) def test_get_account_by_id(self): account = self.instagram.get_account_by_id(3) self.assertEqual('kevin', account.username) self.assertEqual('3', account.identifier) def test_get_medias(self): medias = self.instagram.get_medias('kevin', 80) self.assertEqual(80, len(medias)) def test_get_hundred_medias(self): medias = self.instagram.get_medias('kevin', 100) self.assertEqual(100, len(medias)) def test_get_medias_by_tag(self): medias = self.instagram.get_medias_by_tag('youneverknow', 20) self.assertEqual(20, len(medias)) def test_get_medias_by_code(self): media = self.instagram.get_medias_by_code('BHaRdodBouH') self.assertEqual('kevin', media.owner.username) def test_get_media_by_url(self): media = self.instagram.get_media_by_url('https://www.instagram.com/p/BHaRdodBouH') self.assertEqual('kevin', media.owner.username) def test_get_account_by_id_with_invalid_numeric_id(self): # sys.maxsize is far larger than the greatest id so far and thus does not represent a valid account. try: self.instagram.get_account_by_id(sys.maxsize) except Exception as e: self.assertEqual(str(e), 'Failed to fetch account with given id') def test_get_location_top_medias_by_id(self): medias = self.instagram.get_current_top_medias_by_tag_name(1) self.assertEqual(9, len(medias)) def test_get_location_medias_by_id(self): medias = self.instagram.get_medias_by_location_id(1, 56) self.assertEqual(56, len(medias)) def test_get_location_by_id(self): location = self.instagram.get_location_by_id(1) self.assertEqual('Dog Patch Labs', location.name) def test_get_id_from_code(self): code = Media.get_code_from_id('1270593720437182847') self.assertEqual('BGiDkHAgBF_', code) code = Media.get_code_from_id('1270593720437182847_3') self.assertEqual('BGiDkHAgBF_', code) code = Media.get_code_from_id(1270593720437182847) self.assertEqual('BGiDkHAgBF_', code) def test_get_code_from_id(self): id = Media.get_id_from_code('BGiDkHAgBF_') self.assertEqual(1270593720437182847, id) def test_get_media_comments_by_code(self): comments = self.instagram.get_media_comments_by_code('BR5Njq1gKmB', 40) #TODO: check why returns less comments self.assertLessEqual(40, len(comments)) def test_get_username_by_id(self): username = self.instagram.get_username_by_id(3) self.assertEqual('kevin', username) def test_get_medias_by_user_id(self): medias = self.instagram.get_medias_by_user_id(3) self.assertEqual(12, len(medias))
from igramscraper.instagram import Instagram import json instagram = Instagram() # authentication supported #instagram.with_credentials('usua', 'contrasena') #instagram.login() #Getting an account by id #account = instagram.get_account_by_id(3) #or #Getting an account by username account = instagram.get_account('_tontaku_') # Available fields datos = [ { 'Id':account.identifier, 'Username':account.username, 'Full_name':account.full_name, 'Biography':account.biography, #'Profile pic url: ': account.get_profile_picture_url, 'External_Url':account.external_url, 'Number_of_published_posts':account.media_count, 'Number_of_followers':account.followed_by_count, 'Number_of_follows':account.follows_count, 'Is_private':account.is_private,
from igramscraper.instagram import Instagram import os from time import sleep import pickle instagram = Instagram() # authentication supported username = os.environ.get('IG_USERNAME') password = os.environ.get('IG_PASSWORD') instagram.with_credentials(username, password) instagram.login() account = instagram.get_account('aniruddhavpatil') # Available fields # print('Account info:') # print('Id: ', account.identifier) # print('Username: '******'Full name: ', account.full_name) # print('Biography: ', account.biography) # print('External Url: ', account.external_url) # print('Number of published posts: ', account.media_count) # print('Number of followers: ', account.followed_by_count) # print('Number of follows: ', account.follows_count) # print('Is private: ', account.is_private) # print('Is verified: ', account.is_verified) # or simply for printing use # print(account)
class InstaAgent(): def __init__(self, username, password): self.username = username self.password = password self.scraper = Instagram() self.target = self.scraper.get_account(username) self.scraper.with_credentials(username, password) self.scraper.login() def get_following_data(self, target_name, tweet_count=None): rows = [[ 'username', 'full name', 'biography', 'prive', 'verfied', 'picture' ]] target = self.scraper.get_account(target_name) if not tweet_count: tweet_count = target.follows_count followers = self.scraper.get_following(target.identifier, tweet_count, 100, delayed=True) for item in followers['accounts']: rows.append([ item.username, item.full_name, item.biography, item.is_private, item.is_verified, item.profile_pic_url ]) return rows def get_followers_data(self, target_name, tweet_count=None): rows = [[ 'username', 'full name', 'biography', 'prive', 'verfied', 'picture' ]] target = self.scraper.get_account(target_name) if not tweet_count: tweet_count = target.follows_count followers = self.scraper.get_followers(target.identifier, tweet_count, 100, delayed=True) for item in followers['accounts']: rows.append([ item.username, item.full_name, item.biography, item.is_private, item.is_verified, item.profile_pic_url ]) return rows def substract_folowing_folowers(self, target): following = self.get_following_data(target, tweet_count=650) followers = self.get_followers_data(target, tweet_count=650) res = [ i for i in following if (i not in followers and not i.is_verified) ] res.index(following[0], 0) with open('./CSVs/' + target + '__following.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(following) with open('./CSVs/' + target + '__followers.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(followers) with open('./CSVs/' + target + '__substract.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(res) def unfollow_list(self, lst): for i in lst: try: target = self.scraper.get_account(i) self.scraper.unfollow(target.identifier) print('unfollowed: ' + i) except Exception as e: print(e)
def account_by_username(username: str, client: Instagram, config: dict, logger: logging.Logger) -> Account: return account_from_obj(client.get_account(username))
class InstagramAnalyzer: def __init__(self, username, password): self.instagram = Instagram() self._login(username, password) self.likes = {} self.month_posts = {} self.shared_followings = [] self.likes_contributors = {} def _login(self, username, password): self.instagram.with_credentials(username, password) self.instagram.login() def analyze(self, args, **kwargs): for arg in args: if len(args) != 1: self._find_shared_following(arg) medias = self.instagram.get_medias(arg, count=kwargs['count']) self._count_total_likes(arg, medias) self._count_posts_in_month(arg, medias) self._count_likes_contributor(arg, medias) def _count_total_likes(self, username, medias): total_likes = 0 for media in medias: total_likes += media.likes_count self.likes[username] = total_likes def _count_posts_in_month(self, username, medias): start = datetime.now() month_count = {} for media in medias: date = datetime.fromtimestamp(media.created_time) year_month = f'{date.year}-{date.month}' if diff_month(start, date) > 1: start = date month_count[year_month] = 1 elif diff_month(start, date) <= 1: if year_month in month_count.keys(): month_count[year_month] += 1 else: month_count[year_month] = 1 self.month_posts[username] = month_count def _count_likes_contributor(self, arg, medias): contributor_likes = {} for media in medias: accounts = self.instagram.get_media_likes_by_code( media.short_code, 40)['accounts'] for account in accounts: key = account.username if arg not in self.likes_contributors.keys(): self.likes_contributors[arg] = {} if key not in contributor_likes.keys(): contributor_likes[key] = 1 else: contributor_likes[key] += 1 contributor_likes = dict( sorted(contributor_likes.items(), key=operator.itemgetter(1), reverse=True)[:5]) self.likes_contributors[arg] = contributor_likes def _find_shared_following(self, arg): account = self.instagram.get_account(arg) following = self.instagram.get_following( account.identifier, 200, 100, delayed=True)['accounts'] following_username = self._populate_following_username(following) if len(self.shared_followings) == 0: self.shared_followings = following_username else: self.shared_followings = list( set(self.shared_followings).intersection(following_username)) @staticmethod def _populate_following_username(following): following_username = set() for account in following: following_username.add(account.username) return following_username
def start(request): request_json = request.get_json() insta_username = request_json['insta_username'] insta_password = request_json['insta_password'] username = request_json['username'] discord_webhook_url = request_json['discord_webhook_url'] try: instagram = Instagram() instagram.with_credentials(insta_username, insta_password) instagram.login(force=False, two_step_verificator=True) sleep(2) # Delay to mimic user followers = [] account = instagram.get_account(username) sleep(1) curr_time = datetime.datetime.now(timezone('US/Eastern')) curr_time = curr_time.strftime("%b %d, %Y - %H:%M:%S") followers = instagram.get_followers( account.identifier, FOLLOWER_LIMIT, 100, delayed=True ) # Get 150 followers of 'kevin', 100 a time with random delay between requests # print(followers) followings = instagram.get_following(account.identifier, FOLLOWER_LIMIT, 100, delayed=True) current_followers = [] current_followings = [] for following in followings['accounts']: current_followings.append(following.username) for follower in followers['accounts']: current_followers.append(follower.username) del followers del followings not_follow_back = check_not_followback(current_followings, current_followers) if not path.exists(username + "_follower_list.txt"): f = open(username + "_follower_list.txt", "w") f.write(str(current_followers)) f.close() else: f = open(username + "_follower_list.txt", "r+") old_followers = f.read() f.close() old_followers = ast.literal_eval(old_followers) unfollowers = check_unfollowers(current_followers, old_followers) followers = check_followers(current_followers, old_followers) follower_change = len(current_followers) - len(old_followers) follow_count = len(followers) unfollow_count = len(unfollowers) discord_webhook.send_msg(username, follower_change, followers, unfollowers, follow_count, unfollow_count, curr_time, discord_webhook_url, not_follow_back) retMap = { 'username': username, 'follower_change': follower_change, 'followers': followers, 'unfollowers': unfollowers, 'follow_count': follow_count, 'unfollow_count': unfollow_count, 'curr_time': curr_time, 'discord_webhook_url': discord_webhook_url, 'not_follow_back': not_follow_back } f = open(username + "_follower_list.txt", "w") f.write(str(current_followers)) f.close() retJson = json.dumps(retMap) except Exception as e: print(e)
from igramscraper.instagram import Instagram instagram = Instagram() # authentication supported instagram.with_credentials('', '') instagram.login() #Getting an account by id account = instagram.get_account('bluck') # Available fields '''print('Account info:') print('Id: ', account.identifier) print('Username: '******'Full name: ', account.full_name) print('Biography: ', account.biography) print('External Url: ', account.external_url) print('Number of published posts: ', account.media_count) print('Number of followers: ', account.followed_by_count) print('Number of follows: ', account.follows_count) print('Is private: ', account.is_private) print('Is verified: ', account.is_verified)''' followers = instagram.get_followers(account.identifier, 90, 90, delayed=True) for follower in followers['accounts']: print('bluck ', follower.username) account = instagram.get_account('erick.rojas.988') followers = instagram.get_followers(account.identifier, 90, 90, delayed=True)
from igramscraper.instagram import Instagram import random_proxy instagram = Instagram() account = instagram.get_account('cars') def insta_proxy_requests(): while: try: proxy = random_proxy.get_proxy() r = instagram.set_proxies(proxy, timeout=5) break except: pass return r
class InstaParser: """Получаем информацию из Инстаграма """ def __init__(self, set_proxy: bool = False): config = configparser.ConfigParser() config.read(settings.CONFIG_INI_PATH) self.instagram = Instagram() # self.instagram.with_credentials( # config['INSTA']['LOGIN'], # config['INSTA']['PASSWORD']) # self.instagram.login() if set_proxy: # Нужно расширить список адресов, чтобы Инста не блокировала proxies = { 'http': 'http://123.45.67.8:1087', 'https': 'http://123.45.67.8:1087', } self.instagram.set_proxies(proxies) def get_account_info(self, account: str) -> Dict: """Мета-информация об аккаунте """ account = self.instagram.get_account(account) return { 'posts_count': account.media_count, 'followers': account.followed_by_count, 'follows': account.follows_count } def get_last_posts(self, account: str) -> List[Dict]: """Получаем 100 последних постов аккаунта """ try: medias = self.instagram.get_medias(account, 100) except: medias = [] result = [] for media in medias: if media.caption is not None: result.append({'id': media.identifier, 'text': media.caption, 'date': datetime.datetime.fromtimestamp(media.created_time), 'likes': media.likes_count, 'url': media.link }) return result def get_comments_by_id(self, post_id: str) -> List[Dict]: """Получаем последние 100 комментариев к посту по ID """ comments = self.instagram.get_media_comments_by_id(post_id, 100) result = [] if 'comments' in comments: for comment in comments['comments']: result.append({ 'date': datetime.datetime.fromtimestamp(comment.created_at), 'text': comment.text, '_is_fake': comment._is_fake, 'id': comment.identifier, 'from_username': comment.owner.username, 'from_full_name': comment.owner.full_name }) return result def get_comments_by_code(self, code: str) -> List[Dict]: """Получаем последние 100 комментариев к посту по коду (Работает через раз) Args: code (str): Код поста Returns: List[Dict]: Список комментариев с мета-информацией """ comments = self.instagram.get_media_comments_by_code(code, 100) result = [] if 'comments' in comments: for comment in comments['comments']: result.append({ 'date': datetime.datetime.fromtimestamp(comment.created_at), 'text': comment.text, '_is_fake': comment._is_fake, 'id': comment.identifier, 'username': comment.owner.username, 'from_full_name': comment.owner.full_name }) return result def get_post_by_url(self, url: str) -> Dict: """Получаем пост по URL Args: url (str): Ссылка на пост Returns: Dict: Информация о посте """ media = self.instagram.get_media_by_url(media_url=url) return { 'id': media.identifier, 'text': media.caption, 'date': datetime.datetime.fromtimestamp(media.created_time), 'likes': media.likes_count } def url2acc(self, url: str) -> str: """Извлекает из ссылки на аккаунт имя аккаунта Args: url (str): Ссылка на аккаунт. Например: https://www.instagram.com/new_ulyanovsk/ Returns: str: Аккаунт для применения в методах парсинга: new_ulyanovsk """ return url.split('https://www.instagram.com/')[1].split('/')[0] def url2code(self, url: str) -> str: """Получаем код поста из url Args: url (str): Ссылка на пост. Например: https://www.instagram.com/p/CHDn3eMMenH Returns: str: Код поста: CHDn3eMMenH """ return url.split('https://www.instagram.com/p/')[1].split('/')[0] def get_post_likes(self, code: str) -> int: """Получаем количество лайков поста по его коду Args: code (str): Код поста Returns: int: Количество лайков """ return self.instagram.get_media_likes_by_code(code)
from igramscraper.instagram import Instagram instagram = Instagram() data = {'account': {}} # authentication supported # instagram.with_credentials('covid.ai', 'CoronaCann09') # instagram.login() # #Getting an account by id account = instagram.get_account('covid.ai') data['account']['id'] = account.identifier data['account']['username'] = account.username data['account']['Full name'] = account.full_name data['account']['Biography'] = account.biography data['account']['Profile pic url'] = account.get_profile_picture_url() data['account']['Number of published posts'] = account.media_count data['account']['Number of followers'] = account.followed_by_count data['account']['Number of follows'] = account.follows_count total_likes = 0 total_comments = 0 coms = [] medias = instagram.get_medias("covid.ai", 1000) for x in medias: total_likes += x.likes_count total_comments += x.comments_count comments = instagram.get_media_comments_by_id(x.identifier, 10000) for comment in comments['comments']: coms.append(comment.text) data['comments'] = coms data['total_likes'] = total_likes
from igramscraper.instagram import Instagram # If account is public you can query Instagram without auth instagram = Instagram() # For getting information about account you don't need to auth: account = instagram.get_account('kevin') # Available fields print('Account info:') print('Id', account.identifier) print('Username', account.username) print('Full name', account.full_name) print('Biography', account.biography) print('Profile pic url', account.get_profile_picture_url()) print('External Url', account.external_url) print('Number of published posts', account.media_count) print('Number of followers', account.followed_by_count) print('Number of follows', account.follows_count) print('Is private', account.is_private) print('Is verified', account.is_verified)
# %% str2 = str( '@The.Holistic.Psychologist@kimberleyquinlan@[email protected]@mindfulmft@LisaOliveraTherapy@NedraTawwab@SitWithWhit@[email protected]' ) influencer_name = str2.split('@') influencer_name.remove('') print(influencer_name) # %% # If account is public you can query Instagram without auth instagram = Instagram() # getting information about account for i in influencer_name: account = instagram.get_account(i) # if we can get the data print('Username', account.username) print('Is private', account.is_private) print('\n') # %% list1 = [] for i in influencer_name: #print(i) medias = instagram.get_medias(i, 50) #list1 = [] for i in range(50): media = medias[i] a = str(media)