-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathscrape.py
executable file
·654 lines (603 loc) · 23.8 KB
/
scrape.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
#!/usr/bin/python
import glob, httplib, json, os, re, time, urllib2
from bs4 import BeautifulSoup
import sys
APP_ID = str(sys.argv[1])
APP_SECRET = str(sys.argv[2])
DISQUS_ID = str(sys.argv[3])
DISQUS_SECRET = str(sys.argv[4])
def scrapeAddicting(webpage):
"""scrapes important info from an Addicting Info _webpage_"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page)
#the body text is all contained in <p> tags
raw_text = soup.body.find_all('p')
text = []
for para in raw_text:
if para.get_text():
if not para.find('em'): #not part of the body text
text.append(para.get_text())
links = para.find_all('a')
if links:
for link in links:
link_url = link['href']
link_text = link.get_text()
articleJSON['links'].append([link_url, link_text])
if 'https://twitter.com' in link_url:
if 'status' in link_url:
articleJSON['tweets'].append(link_url)
#now get the pictures
pics = para.find_all('img')
if pics:
for pic in pics:
pic_url = pic['src']
pic_text = pic.get('alt', '')
articleJSON['pictures'].append([pic_url, pic_text])
articleJSON['body'] = " ".join(text)
#no Disqus or FB comments
"""
There is no robots.txt for the Addicting Info site, and no mention
of rate limiting. In this case, wait 30 seconds between scrapes,
just to be safe.
"""
time.sleep(30)
return articleJSON
def scrapePolitico(webpage):
"""takes the url of a politi.co article and scrapes important info
using BeautifulSoup"""
#pictures key will have a list of tuples of image link and its caption
#links key will be list of tuples of link and its naming
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page, 'html5lib')
#first find the figures and their captions
figures = soup.find_all('figure', class_ = 'art')
if figures:
for figure in figures:
captions = figure.find_all('p', class_ = '')
if captions:
caption = captions[0].get_text().strip()
else:
caption = ""
images = figure.find_all('img')
if images:
if images[0]['src']:
image = images[0]['src']
else:
image = ""
else:
image = ""
articleJSON["pictures"].append((image, caption))
#now find the links and their text
links = [x
for x in soup.body.find_all('a')
if x.parent.name == 'p']
#the last one is just an ad
if links:
for link in links:
#get rid of the ad at the bottom for some of the articles
if not link.parent.get('class'):
link.parent['class'] = ''
if link.get_text() != 'POLITICO Playbook':
if link.parent['class'] != 'category':
url = link['href'] if link['href'] else ""
text = link.get_text().strip()
articleJSON['links'].append((url, text))
paras = [x
for x in soup.body.find_all('p', class_ = "")
if x.parent.name != "figcaption"]
#these are the <p> tags with the body text, minus those for figs
#and the blurbs at the bottom
if paras:
raw_text = [x.get_text().strip() for x in paras]
#seems like the last <p> is just going to be an ad, delete it
article = " ".join(raw_text[:-1])
articleJSON["body"] = article
#get tweets
articleJSON['tweets'] = getTweets(soup)
#just FB comments
"""
The robots.txt file and Terms of Service for the Politico site
makes no mention of rate limiting. So let's just go with the
standard.
"""
time.sleep(30)
return articleJSON
def scrapeRightWing(webpage):
"""scrapes important info from RightWingNews articles"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page, 'html5lib')
raw_text = soup.body.find_all('p')
#get the body text and the links
text = []
for para in raw_text:
if 'main-article' in para.parent.get('class', []): #just want content
if para.get_text():
text.append(para.get_text().strip())
#get the links here too
links = para.find_all('a')
if links:
for link in links:
link_url = link['href']
link_text = link.get_text()
articleJSON['links'].append([link_url, link_text])
body = " ".join(text)
articleJSON['body'] = body
#now scrape the pictures
centered = soup.body.find_all('center')
photos = soup.find_all('img', class_ = 'article-photo')
for photo in photos:
photo_text = photo.get_text().strip()
photo_url = photo['src']
articleJSON['pictures'].append([photo_text, photo_url])
for center in centered:
images = center.find_all('img')
for image in images:
image_text = image.get_text().strip()
image_url = image['src']
articleJSON['pictures'].append([image_url, image_text])
articleJSON['tweets'] = getTweets(soup)
#just FB comments
"""
The robots.txt file for Right Wing News says there must be a
delay of 30 seconds between scrapes, so that's what we'll do.
There is no mention of restrictions in the Terms of Service.
"""
time.sleep(30)
return articleJSON
def scrapeEagle(webpage):
"""scrapes important info from Eagle Rising articles"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page)
text = []
raw_text = soup.article.find_all('p')
for para in raw_text:
if para.get_text():
text.append(para.get_text().strip())
#get the links
links = para.find_all('a')
if links:
for link in links:
link_url = link['href']
link_text = link.get_text().strip()
articleJSON['links'].append([link_url, link_text])
#get the images
images = para.find_all('img')
if images:
for image in images:
image_url = image.get('src')
image_caption = image.get('alt').strip()
articleJSON['pictures'].append([image_url, image_caption])
articleJSON['body'] = " ".join(text)
articleJSON['tweets'] = getTweets(soup)
#has both FB and Disqus comments!
articleJSON['DisqComm'] = getDisqComments(webpage, forum = 'eaglerising')
"""
The robots.txt file for Eagle Rising designates the delay time to be
10 seconds, so that's what we'll use. The Terms of Service make no mention
of it.
"""
time.sleep(10)
return articleJSON
def scrapeOccupy(webpage):
"""scrapes important info from OccupyDemocrats articles"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page, 'lxml')
#get the main article image
main_pic = soup.find_all('img', class_ = "attachment- size- wp-post-image")
if main_pic:
main_url = main_pic[0]['src']
main_caption = main_pic[0].get_text().strip()
articleJSON['pictures'].append([main_url, main_caption])
other_pics = soup.body.find_all('img')
other_pics = [x
for x in other_pics
if x.parent.name == 'p']
if other_pics:
for other_pic in other_pics:
other_cap = other_pic.get_text()
other_url = other_pic['src']
articleJSON['pictures'].append([other_url, other_cap])
articles = soup.body.find_all('article')
raw_text = [x
for x in articles[0].find_all('p', class_ = '', lang='', dir='')
if x.get_text() != ''][1:-1]
#this removes the author blurbs and blank <p>s
#get the body links and pics
text = []
for para in raw_text:
text.append(para.get_text().strip())
#links
if para.find_all('a'):
for link in para.find_all('a'):
url = link['href']
link_text = link.get_text().strip()
articleJSON['links'].append([url, link_text])
#pictures
if para.find_all('img'):
for pic in para.find_all('img'):
pic_url = pic['src']
pic_caption = pic.get_text().strip()
articleJSON['pictures'].append([pic_url, pic_caption])
articleJSON['body'] = " ".join(text)
articleJSON['tweets'] = getTweets(soup)
#just FB comments
"""
The Occupy Democrats robot.txt makes no mention of rate-limiting,
so we'll just use the default.
"""
time.sleep(30)
return articleJSON
def scrapeCNN(webpage):
"""scrapes important info from CNN articles"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page, 'lxml')
raw_text = soup.body.find_all(class_ = 'zn-body__paragraph')
pictures = []
metas = soup.find_all('meta')
for meta in metas:
if meta:
if 'content' in meta.attrs.keys():
try:
if (meta['content'][:7] == 'http://'
and meta['content'][-4:] == '.jpg'):
pictures.append(meta['content'])
except:
print "bad url!"
#AFAIK cnn doesn't have captions on its vids
articleJSON['pictures'] = [(pic, '') for pic in set(pictures)]
#now get the links
links = []
text = []
for para in raw_text:
if para.get_text():
text.append(para.get_text().strip())
if para.find_all('a'):
for link in para.find_all('a'):
url = link['href']
link_text = link.get_text().strip()
links.append([url, link_text])
#get the tweets, just the URLS
articleJSON['tweets'] = getTweets(soup)
articleJSON['body'] = " ".join(text)
articleJSON['links'] = links
#no comments
"""
The robots.txt for CNN makes no mention of rate-limiting, so
let's just use the default value. The Terms of Service make no
mention of it.
"""
time.sleep(30)
return articleJSON
def scrapeFreedom(webpage):
"""scrapes articles on Freedom Daily website"""
articleJSON, page = createPage(webpage)
soup = BeautifulSoup(page, 'lxml')
text = []
raw_text = soup.body.article.find_all('p')
if raw_text:
for para in soup.body.article.find_all('p'):
#body text
if para.get_text().strip():
text.append(para.get_text().strip())
#links
if para.find_all('a'):
for link in para.find_all('a'):
url = link['href']
link_text = link.get_text().strip()
articleJSON['links'].append([url, link_text])
#get images
images = soup.body.article.find_all('img')
if images:
for image in soup.body.article.find_all('img'):
image_url = image.get('src', '')
image_caption = image.get('title', '')
articleJSON['pictures'].append([image_url, image_caption])
articleJSON['tweets'] = getTweets(soup)
articleJSON['body'] = " ".join(text)
#just FB comments
"""
The robots.txt for Freedom Daily makes no mention of
rate-limiting, so let's just use the default.
"""
time.sleep(30)
return articleJSON
def scrape98(webpage):
"""scrapes The Other 98% pages"""
#there are 12 Occupy Democrat articles in here, so we can just use the
#function we already made. then there are around 75 facebook links,
#which are just photos or videos. the actual articles are mainly
#usuncut.com, so should make a scraper for that.
#first take care of Occupy articles
if 'http://occupydemocrats.com' in webpage:
return scrapeOccupy(webpage)
elif 'http://usuncut.com' in webpage:
return scrapeUncut(webpage)
else: #facebook links, other stuff.
return {}
def scrapeUncut(webpage):
"""scrapes the US Uncut links found in the 98% articles"""
# this site is down??
return {}
def scrapeABC(webpage):
"""scrape ABC News articles"""
articleJSON, page = createPage(webpage)
text = []
if page:
#check for redirect here
if page.geturl() != "http://abcnews.go.com":
soup = BeautifulSoup(page, 'lxml')
raw_text = soup.body.find_all('p', itemprop = 'articleBody')
for para in raw_text:
if para.get_text().strip():
text.append(para.get_text().strip())
#get links
links = para.find_all('a')
if links:
for link in links:
link_url = link.get('href', '')
link_text = link.get_text()
articleJSON['links'].append([link_url, link_text])
pics = soup.body.find_all('picture')
for pic in pics:
picture = pic.find('img')
articleJSON['pictures'].append([picture.get('src', '').strip(), picture.get('alt', '').strip()])
articleJSON['tweets'] = getTweets(soup)
articleJSON['body'] = " ".join(text)
#just Disqus comments
articleJSON['DisqComm'] = getDisqComments(webpage, 'abcnewsdotcom')
"""
The robots.txt makes no mention of rate-limiting, so we'll use the default.
Terms of Service makes no mention either.
"""
time.sleep(30)
return articleJSON
def getTweets(soup):
"""scrapes the embedded tweets on pages. they seem to be the same format on
the different websites. takes a soup object in and gives back a list of
tweet urls"""
article_tweets = []
tweets = soup.body.find_all('blockquote', class_ = 'twitter-tweet')
if tweets:
for tweet in tweets:
tweet_urls = tweet.find_all('a')
temp = [tweet['href'] for tweet in tweet_urls]
real_urls = filter(lambda x: True if 'status' in x else False,
temp)
article_tweets.extend(real_urls)
return article_tweets
def createPage(webpage):
"""given a _webpage_ will set up the right environment and then opens and
returns the page using urllib2"""
articleJSON = {
"body" : "",
"pictures" : [],
"links" : [],
"tweets" : [],
"comments" : [],
"DisqComm" : [] #keep the Disqus comments separate
}
page = openPage(webpage)
return articleJSON, page
def openPage(webpage):
"""given a webpage, opens the page in Python and returns it"""
#to avoid 403 errors, need to make the request as a browser
web_response = None
hdr = {'User-agent' : 'Mozilla/5.0'}
req = urllib2.Request(webpage, headers=hdr)
#open the page, try to catch all exceptions
try:
web_response = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
except urllib2.URLError, e:
#print e.fp.read()
print "URL ERROR ", wepage
except httplib.HTTPException, e:
#print e.fp.read()
print "HTTP EXCEPTION ", webpage
except Exception, e:
print "other exception loading the page: ", webpage
return web_response
def createCommentsURL(webpage, APP_ID, APP_SECRET):
"""some of the articles have embedded facebook comments. this will create
the correct URL to grab these comments in JSON form"""
#to scrape fb comments on other urls first need to find the ID number
#assigned to the page by fb
ID_URL = 'https://graph.facebook.com/?ids='
url = ID_URL + webpage
web_response = openPage(url)
if web_response:
readable_page = web_response.read()
else:
return None
try:
data = json.loads(readable_page)
except:
print "problem loading comment json"
return None
try:
#the graph API requires an ID number to access comments
ID_NUM = data[webpage]['og_object']['id']
comments_args = "/comments?access_token=" + APP_ID + "|" + APP_SECRET + \
"&filter=stream"
comments_url = ("https://graph.facebook.com/v2.10/" +
ID_NUM + comments_args)
except:
print "problem assigning fb comments URL"
comments_url = ""
return comments_url
def getComments(webpage, n = 1):
"""fetches the embedded facebook plugin comments for the article at
_webpage_. returns the data in a JSON. can't use the collectPosts version
because that only works for facebook posts."""
comments_url = createCommentsURL(webpage, APP_ID, APP_SECRET)
data = []
if comments_url:
time.sleep(n)
web_response = openPage(comments_url)
if web_response:
readable_page = web_response.read()
else:
return {}
try:
thisdata = json.loads(readable_page)
data.extend(thisdata['data'])
except:
print "loading comment didn't work"
if 'paging' in thisdata.keys():
while thisdata['paging'].get('next', False):
try:
time.sleep(n)
web_response = urllib2.urlopen(thisdata['paging']['next'])
if web_response:
thisdata = json.loads(web_response.read())
if thisdata['data']:
data.extend(thisdata['data'])
except:
print "problem getting extra batches"
return data
def createDisqURL(webpage, DISQUS_ID, DISQUS_SECRET, forum):
"""some of the articles have embedded disqus comments. this will create the
correct URL to make API requests"""
try:
if forum == 'abcnewsdotcom':
_, page = createPage(webpage) #take care of redirects
url = page.geturl()
page = openPage(url)
soup = BeautifulSoup(page)
ID = soup.body.find('article')['data-id'] #get the ID of the article
split = re.split('/', url[7:]) #need to reformat the link
webpage = 'http://' + split[0] + '/' + split[1] + '/story?id=' + ID
args = '&thread=link:' + webpage + '&forum=' + forum
comments_url = ('https://disqus.com/api/3.0/threads/listPosts.json?api_key=' +
DISQUS_ID + '&api_secret=' + DISQUS_SECRET + args)
except:
print "problem creating Disqus URL"
comments_url = ""
return comments_url
def getDisqComments(webpage, forum, n = 1):
"""makes the requests to get the Disqus comments for a given _webpage_,
also requires the _forum_ name for the page as per the API"""
comments_url = createDisqURL(webpage, DISQUS_ID, DISQUS_SECRET, forum)
data = []
if comments_url:
time.sleep(n)
web_response = openPage(comments_url)
if web_response:
readable_page = web_response.read()
else:
return {}
try:
thisdata = json.loads(readable_page)
data.extend(thisdata['response'])
except:
print "loading comments didn't work"
return {}
if 'cursor' in thisdata.keys():
while thisdata['cursor']['hasNext']:
"""
I'm not 100% sure what the rate limit is for the Disqus API,
can't find it in the documentation. To be safe, just use the
same rate we've been using for the facebook comments.
"""
time.sleep(n)
next_cursor = thisdata['cursor']['next']
extra_comments_url = comments_url + '&cursor=' + next_cursor
try:
web_response = openPage(extra_comments_url)
except:
print "web response"
continue
try:
readable_page = web_response.read()
except:
print "readable page"
continue
try:
thisdata = json.loads(readable_page)
if thisdata.get('response', False):
data.extend(thisdata['response'])
except:
print "json load?"
continue
return data
def outlet_scrape(outlet):
"""given an _outlet_ will scrape all articles contained in that folder"""
outletDict = {
"Politico" : scrapePolitico,
"CNN_Politics" : scrapeCNN,
"Right_Wing_News" : scrapeRightWing,
"Occupy_Democrats" : scrapeOccupy,
"Eagle_Rising" : scrapeEagle,
"Addicting_Info" : scrapeAddicting,
"Freedom_Daily" : scrapeFreedom,
"The_Other_98%" : scrape98,
"ABC_News_Politics" : scrapeABC
}
path = './dataset/' + outlet + '/'
files = glob.glob(path + '*/posts.json')
num = len(files)
for i, filename in enumerate(files):
print "working on: " + filename
print str(i + 1) + " / " + str(num)
fileJSON = {}
with open(filename, 'r') as f:
postJson = json.load(f)
if "link" not in postJson.keys():
print "no link!", filename
continue #if the link is missing, skip
if "type" not in postJson.keys():
print "no type! ", filename
#for now just skip video and pic posts
if postJson.get('type') == 'video':
fileJSON = {
"body" : postJson.get('message', ''),
"links" : [postJson.get('source', ''), ''],
"pictures" : [postJson.get('picture', ''), postJson.get('name', '')]
}
elif postJson.get('type') == 'photo':
fileJSON = {
"body" : '',
"links" : [postJson.get('link', ''), postJson.get('story', '')],
"pictures" : [postJson.get('picture', ''), postJson.get('name', '')]
}
else:
#if the post is an article, scrape it
if 'link' not in postJson.keys():
print "no link!"
continue
webpage = postJson["link"]
if outlet == "The_Other_98%":
#The Other 98% seems to have NO first party articles, so handle
#this case separately
try:
fileJSON = scrape98(webpage)
except:
print "scraping didn't work! ", webpage
fileJSON['comments'] = getComments(webpage)
else:
#these scrapers are only useful for first party articles
if postJson["first_party"]:
try:
fileJSON = outletDict[outlet](webpage)
except:
print "scraping didn't work! ", webpage
fileJSON['comments'] = getComments(webpage)
#chop off the posts.json of the filename and add scraped.json
new_filename = filename[:-10] + 'scraped.json'
#now dump the scraped JSONs in the same folder
with open(new_filename, 'w') as f2:
json.dump(fileJSON, f2, indent = 4, sort_keys = True)
if __name__ == '__main__':
outlets = ['ABC_News_Politics',
'Addicting_Info',
'CNN_Politics',
'Eagle_Rising',
'Freedom_Daily',
'Occupy_Democrats',
'Politico',
'Right_Wing_News',
'The_Other_98%']
for outlet in outlets:
if os.path.isdir('./dataset/' + outlet):
outlet_scrape(outlet)