]> code.communitydata.science - covid19.git/blob - wikipedia_views/scripts/fetch_daily_views.py
18bc01fdd512a7268d6377a7261be0a236701524
[covid19.git] / wikipedia_views / scripts / fetch_daily_views.py
1 #!/usr/bin/env python3
2
3 ###############################################################################
4 #
5 # This script assumes the presence of the COVID-19 repo.
6
7 # It (1) reads in the article list and then (2) calls the Wikimedia API to 
8 # fetch view information for each article. Output is to (3) JSON and TSV.
9 #
10 ###############################################################################
11
12
13 import requests
14 import argparse
15 import json
16 import csv
17 import time
18 import os.path
19 import datetime
20 #import feather
21
22
23 def parse_args():
24
25     parser = argparse.ArgumentParser(description='Call the views API repeatedly.')
26     parser.add_argument('-o', '--output_folder', help='Where to save output', default="../data/", type=str)
27     parser.add_argument('-i', '--article_file', help='File listing article names', default="../resources/articles.txt", type=str)
28     parser.add_argument('-d', '--query_date', help='Date if not yesterday, in YYYYMMDD format please.', type=str)
29     args = parser.parse_args()
30
31     return(args)
32
33
34 def main():
35
36     args = parse_args()
37
38     outputPath = args.output_folder
39     articleFile = args.article_file
40
41     if (args.query_date):
42         queryDate = args.query_date
43     else:
44         yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
45         queryDate = yesterday.strftime("%Y%m%d")
46
47     queryDate = queryDate + "00" #requires specifying hours
48
49
50     articleList = []
51     #1 Load up the list of article names
52
53     j_Out = f"{outputPath}dailyviews{queryDate}.json"
54     t_Out = f"{outputPath}dailyviews{queryDate}.tsv"
55
56     with open(articleFile, 'r') as infile:
57         next(infile) #skip header
58         articleList = infile
59
60         j = []
61
62         #2 Repeatedly call the API with that list of names
63
64         for a in articleList:
65             a = a.strip("\"\n") #destringify
66             url= f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{a}/daily/{queryDate}/{queryDate}"
67
68             response = requests.get(url)
69             if response.ok:
70                 jd = json.loads(response.content)
71                 j.append(jd["items"][0])
72                 time.sleep(.1)
73             else:
74                 print(f"Not ok response: {response.status_code} from {url}")
75                 
76         #3 Save results as a JSON and TSV
77
78     #all data in j now, make json file
79     with open(j_Out, 'w') as j_outfile: 
80         json.dump(j, j_outfile, indent=2)
81
82     with open(t_Out, 'w') as t_outfile:
83         dw = csv.DictWriter(t_outfile, sorted(j[0].keys()), delimiter='\t')
84         dw.writeheader()
85         dw.writerows(j)
86
87
88     # f_Out = outputPath + "dailyviews" + queryDate + ".feather"
89     # read the json back in and make a feather file? 
90
91
92 if __name__ == "__main__":
93
94     main()

Community Data Science Collective || Want to submit a patch?