-
Notifications
You must be signed in to change notification settings - Fork 7
/
export_news.py
executable file
·74 lines (63 loc) · 1.72 KB
/
export_news.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
#!/usr/bin/env python2
# -- coding: utf-8 --
## Need to install google-api-python-clientself.
## pip install --upgrade google-api-python-client
import requests
import unicodecsv
from utils import get_api_key
from dateutil import parser
# GA_product = raw_input('What is your Google Analytics product Key? ')
token = get_api_key()
url = 'https://www.muckrock.com/api_v1/'
headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
next_ = url + 'news'
fields = (
"id",
"authors",
"editors",
"pub_date",
"title",
"kicker",
"slug",
"summary",
"body",
"publish",
"image"
)
field_names = (
"id",
"authors",
"editors",
"pub_date",
"title",
"kicker",
"slug",
"summary",
"body",
"publish",
"image",
"wordcount",
"title_wordcount",
"full_url"
)
page = 1
csv_file = open('news.csv', 'w')
csv_file.seek(0)
csv_writer = unicodecsv.writer(csv_file)
csv_writer.writerow(field_names)
while next_ is not None:
r = requests.get(next_, headers=headers)
try:
json = r.json()
next_ = json['next']
for datum in json['results']:
pack = [datum[field] for field in fields]
datum['wordcount'] = len(datum['body'].split())
datum['title_wordcount'] = len(datum['title'].split())
datum['full_url'] = 'https://www.muckrock.com/news/archives/' + parser.parse(datum['pub_date']).strftime('%Y') + '/' + parser.parse(datum['pub_date']).strftime('%b').lower() + '/' + parser.parse(datum['pub_date']).strftime('%d') + '/' + datum['slug'] + '/'
print datum['full_url']
csv_writer.writerow([datum[field] for field in field_names])
print 'Page %d of %d' % (page, (json['count'] / 50) + 1)
page += 1
except Exception as e:
print e