6 # get_article_revisions is a function that takes an article title in
7 # wikipedia and return a list of all the revisions and meatadata for
9 def get_article_revisions(title):
12 # create a base url for the api and then a normal url which is initially just a copy of it
13 # http://en.wikipedia.org/w/api.php/?action=query&titles=%(article_title)s&prop=revisions&rvprop=flags|timestamp|user|size|ids&rvlimit=500&format=json
14 wp_api_url = "http://en.wikipedia.org/w/api.php/"
16 parameters = {'action' : 'query',
19 'rvprop' : 'flags|timestamp|user|size|ids',
24 # we'll repeat this forever (i.e., we'll only stop when we find
25 # the "break" command)
27 # the first line open the urls but also handles unicode urls
28 call = requests.get(wp_api_url, params=parameters)
29 api_answer = call.json()
31 # get the list of pages from the json object
32 pages = api_answer["query"]["pages"]
34 # for every pages (there should always be only one) get the revisions
35 for page in pages.keys():
36 query_revisions = pages[page]["revisions"]
38 # for every revision, we do first do cleaning up
39 for rev in query_revisions:
40 # lets continue/skip if the user is hidden
41 if "userhidden" in rev:
44 # 1: add a title field for the article because we're going to mix them together
47 # 2: lets "recode" anon so it's true or false instead of present/missing
53 # 3: letst recode "minor" in the same way
59 # we're going to change the timestamp to make it work a little better in excel and similar
60 rev["timestamp"] = rev["timestamp"].replace("T", " ")
61 rev["timestamp"] = rev["timestamp"].replace("Z", "")
63 # finally save the revisions we've seen to a varaible
66 if 'continue' in api_answer:
67 parameters.update(api_answer['continue'])
71 # return all the revisions for this page
74 category = "Harry Potter"
76 # we'll use another api called catscan2 to grab a list of pages in
77 # categories and subcategories. it works like all the other apis we've
80 # http://tools.wmflabs.org/catscan2/catscan2.php?depth=10&categories=%s&doit=1&format=json
81 url_catscan = "http://tools.wmflabs.org/catscan2/catscan2.php"
83 parameters = {'depth' : 10,
84 'categories' : category,
88 r = requests.get(url_catscan, params=parameters)
89 articles_json = r.json()
90 articles = articles_json["*"][0]["a"]["*"]
92 # open a filie to write all the output
93 output = open("hp_wiki.tsv", "w", encoding="utf-8")
94 output.write("\t".join(["title", "user", "timestamp", "size", "anon", "minor", "revid"]) + "\n")
97 for article in articles:
99 # first grab tht title
100 title = article["a"]["title"]
102 # get the list of revisions from our function and then interating through it printinig it out
103 revisions = get_article_revisions(title)
104 for rev in revisions:
105 output.write("\t".join(['"' + rev["title"] + '"', '"' + rev["user"] + '"',
106 rev["timestamp"], str(rev["size"]), str(rev["anon"]),
107 str(rev["minor"]), str(rev["revid"])]) + "\n")
109 # close the file, we're done here!