forked from minimaxir/facebook-page-post-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_fb_comments_from_fb.py
223 lines (168 loc) · 8.33 KB
/
get_fb_comments_from_fb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import json
import datetime
import csv
import time
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen, Request
app_id = "<FILL IN>"
app_secret = "<FILL IN>" # DO NOT SHARE WITH ANYONE!
file_id = "cnn"
access_token = app_id + "|" + app_secret
def request_until_succeed(url):
req = Request(url)
success = False
while success is False:
try:
response = urlopen(req)
if response.getcode() == 200:
success = True
except Exception as e:
print(e)
time.sleep(5)
print("Error for URL {}: {}".format(url, datetime.datetime.now()))
print("Retrying.")
return response.read()
# Needed to write tricky unicode correctly to csv
def unicode_decode(text):
try:
return text.encode('utf-8').decode()
except UnicodeDecodeError:
return text.encode('utf-8')
def getFacebookCommentFeedUrl(base_url):
# Construct the URL string
fields = "&fields=id,message,reactions.limit(0).summary(true)" + \
",created_time,comments,from,attachment"
url = base_url + fields
return url
def getReactionsForComments(base_url):
reaction_types = ['like', 'love', 'wow', 'haha', 'sad', 'angry']
reactions_dict = {} # dict of {status_id: tuple<6>}
for reaction_type in reaction_types:
fields = "&fields=reactions.type({}).limit(0).summary(total_count)".format(
reaction_type.upper())
url = base_url + fields
data = json.loads(request_until_succeed(url))['data']
data_processed = set() # set() removes rare duplicates in statuses
for status in data:
id = status['id']
count = status['reactions']['summary']['total_count']
data_processed.add((id, count))
for id, count in data_processed:
if id in reactions_dict:
reactions_dict[id] = reactions_dict[id] + (count,)
else:
reactions_dict[id] = (count,)
return reactions_dict
def processFacebookComment(comment, status_id, parent_id=''):
# The status is now a Python dictionary, so for top-level items,
# we can simply call the key.
# Additionally, some items may not always exist,
# so must check for existence first
comment_id = comment['id']
comment_message = '' if 'message' not in comment else \
unicode_decode(comment['message'])
comment_author = unicode_decode(comment['from']['name'])
num_reactions = 0 if 'reactions' not in comment else \
comment['reactions']['summary']['total_count']
if 'attachment' in comment:
attach_tag = "[[{}]]".format(comment['attachment']['type'].upper())
comment_message = attach_tag if comment_message is '' else \
comment_message + " " + attach_tag
# Time needs special care since a) it's in UTC and
# b) it's not easy to use in statistical programs.
comment_published = datetime.datetime.strptime(
comment['created_time'], '%Y-%m-%dT%H:%M:%S+0000')
comment_published = comment_published + datetime.timedelta(hours=-5) # EST
comment_published = comment_published.strftime(
'%Y-%m-%d %H:%M:%S') # best time format for spreadsheet programs
# Return a tuple of all processed data
return (comment_id, status_id, parent_id, comment_message, comment_author,
comment_published, num_reactions)
def scrapeFacebookPageFeedComments(page_id, access_token):
with open('{}_facebook_comments.csv'.format(file_id), 'w') as file:
w = csv.writer(file)
w.writerow(["comment_id", "status_id", "parent_id", "comment_message",
"comment_author", "comment_published", "num_reactions",
"num_likes", "num_loves", "num_wows", "num_hahas",
"num_sads", "num_angrys"])
num_processed = 0
scrape_starttime = datetime.datetime.now()
after = ''
base = "https://graph.facebook.com/v2.9"
parameters = "/?limit={}&access_token={}".format(
100, access_token)
print("Scraping {} Comments From Posts: {}\n".format(
file_id, scrape_starttime))
with open('{}_facebook_statuses.csv'.format(file_id), 'r') as csvfile:
reader = csv.DictReader(csvfile)
for status in reader:
has_next_page = True
node = "/{}/comments".format(status['status_id'])
after = '' if after is '' else "&after={}".format(after)
base_url = base + node + parameters + after
url = getFacebookCommentFeedUrl(base_url)
#print(url)
comments = json.loads(request_until_succeed(url))
reactions = getReactionsForComments(base_url)
while has_next_page and comments is not None:
for comment in comments['data']:
comment_data = processFacebookComment(
comment, status['status_id'])
reactions_data = reactions[comment_data[0]]
#print(comment_data + reactions_data)
w.writerow(comment_data + reactions_data)
if 'comments' in comment:
has_next_subpage = True
sub_after = ''
while has_next_subpage:
sub_node = "/{}/comments".format(comment['id'])
sub_after = '' if sub_after is '' else "&after={}".format(
sub_after)
sub_base_url = base + sub_node + parameters + sub_after
sub_url = getFacebookCommentFeedUrl(
sub_base_url)
sub_comments = json.loads(
request_until_succeed(sub_url))
sub_reactions = getReactionsForComments(
sub_base_url)
#print(sub_reactions)
for sub_comment in sub_comments['data']:
sub_comment_data = processFacebookComment(
sub_comment, status['status_id'], comment['id'])
sub_reactions_data = sub_reactions[
sub_comment_data[0]]
w.writerow(sub_comment_data +
sub_reactions_data)
num_processed += 1
if num_processed % 100 == 0:
print("{} Comments Processed: {}".format(
num_processed,
datetime.datetime.now()))
if 'paging' in sub_comments:
if 'next' in sub_comments['paging']:
sub_after = sub_comments[
'paging']['cursors']['after']
else:
has_next_subpage = False
else:
has_next_subpage = False
# output progress occasionally to make sure code is not
# stalling
num_processed += 1
if num_processed % 100 == 0:
print("{} Comments Processed: {}".format(
num_processed, datetime.datetime.now()))
if 'paging' in comments:
if 'next' in comments['paging']:
after = comments['paging']['cursors']['after']
else:
has_next_page = False
else:
has_next_page = False
print("\nDone!\n{} Comments Processed in {}".format(
num_processed, datetime.datetime.now() - scrape_starttime))
if __name__ == '__main__':
scrapeFacebookPageFeedComments(file_id, access_token)
# The CSV can be opened in all major statistical programs. Have fun! :)