Python Instagram Scraper: commenti

Lo scraping dei commenti  può aiutarci ad identificare i migliori commentatori del nostro profilo e la frequenza con cui commentano. Ad esempio il profilo pubblico del Van Gogh Museum, ha proposto in un post pubblico di indovinare quanti girasoli erano dipinti nella famosa opera di Van Gogh.

How many sunflowers are there in this painting?
???? Vincent van Gogh, Sunflowers (1889)




Attraverso lo scrapping si sarebbe in grado di selezionare i vincitori del quiz.

Un possibile esempio di codice potrebbe essere il seguente, recuperando tutti i commenti possiamo controllarne il contenuto parola per parola controllando se è un numero intero.

comments = account.get_post_preview_comments('CPApDNGgiwt')
for comment in comments['comments']:
    text = comment['text']
    numbers = [int(word) for word in text.split() if word.isdigit()]
    for number in numbers:
	if number == 15:
	   print('Profile: {}'.format(comment['owner']))
	   print("Correct Answer")




Scrappando i primi 24 commenti possiamo trovare i profili che avevano risposto correttamente:

Profile: paisley.blue.bear
Correct Answer
Profile: ghinwafayyad
Correct Answer
Profile: nidajudge
Correct Answer
Profile: nani.art_
Correct Answer
Profile: tweddle.samantha
Correct Answer




Per un brand, un influencer questo tipo di analisi può aiutare a conoscere meglio i propri i followers attraverso le loro risposte consentendo di sapere quali post creare e quali strategie utilizzare per trarne vantaggio.

Hashtags

Nel 2011 Instagram, ispirandosi a Twitter, introduce gli hashtags: facendo precedere una parola o una frase da # è possibile condividere i contenuti in base agli interessi.

Per conoscere gli hashtags nella didascalia (caption) di una foto o nel commento di un’utente splittiamo il testo e word by word cerchiamo il simbolo # utilizzando una regex o più semplicemente starstwith.

def extract_tags(self, text, tag='#'):
        tags = list()
        for word in text.split():
            if word[0].startswith(tag):
                tags.append(word[1:])
        return tags




Datamodel

Partendo dal json del commento iniziamo a crearci il datamodel con campi che ci interessano.

{
   "id":"",
   "text":"",
   "created_at": ,
   "did_report_as_spam":false,
   "owner":{
	  "id":"",
	  "is_verified":false,
	  "profile_pic_url":"",
	  "username":""
   },
   "viewer_has_liked":false,
   "edge_liked_by":{
	  "count":1
   },
   "is_restricted_pending":false,
   "edge_threaded_comments":{
	  "count":0,
	  "page_info":{
		 "has_next_page":false,
		 "end_cursor":"None"
	  },
	  "edges":[
	  ]
   }
}




Per il momento useremo il testo del commento (text), l’identificativo (id) , la data di creazione (created_at) ed il proprietario (owner).

from datetime import datetime

class Comment(object):

	def __init__(self, properties=None):
		if properties is not None and len(properties) > 0:
			for key in properties.keys():
				self.custom_properties(properties[key], key)

	def custom_properties(self, value, prop):

		if prop == 'id':
			self.identifier = value
		elif prop == 'text':
			self.text = value
		elif prop == 'created_at':
			readable_date = datetime.fromtimestamp(int(value)).strftime("%d-%m-%Y %H:%M:%S")
			self.created_at = readable_date
		elif prop == 'owner':
			self.owner = value['username']




Sitografia

Instagram

[1] Nilay Patel , No, Instagram can’t sell your photos: what the new terms of service really mean, The Verge, 18/12/2012
[2] Josh Ocampo, Instagram Doesn’t Own Your Photos, But They Can Still Use Them Forever, LifeHacker, 21/8/2019
[3] Ben Gilbert , No, you don’t have to publicly declare that Instagram can’t use your photos — you already said yes when you signed up, Insider, 21/08/2019
[4] Instagram and Copyright: What are the terms of use?, Copyrightlaws, 11/01/2021

GraphQL
[1] Frederic Lardinois, Facebook’s GraphQL gets its own open-source foundation, Techcrunch, 6/11/2018
[2] Instagram Team, Ora puoi programmare i post con l’API Instagram Graph, Facebook for business, 30/01/2018
[3] Instagram Team, Instagram API changes 2020: Instagram Graph API and Basic Display API, 2018

Emoji
[1] Kralj Novak P, Smailović J, Sluban B, Mozetič I (2015) Sentiment of Emoji.