forked from UWPCE-PythonCert/ProgrammingInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
53 lines (40 loc) · 1.3 KB
/
api.py
File metadata and controls
53 lines (40 loc) · 1.3 KB
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
#!/usr/bin/env python
"""
Some code for accessing the Wikipedia API
"""
# Really handy third-party module
# ``pip install requests`` if you don't already have it
import requests
class ParseError(Exception):
pass
class MissingArticleError(Exception):
pass
class Wikipedia:
"""
Wikipedia API interface
https://www.mediawiki.org/wiki/API:Main_page
"""
# base url for the english edition of wikipedia
api_endpoint = "http://en.wikipedia.org/w/api.php?"
@classmethod
def get_article(cls, title):
"""
Return contents of article
:param title: title of article
"""
req_params = {'action': 'parse',
'format': 'json',
'prop': 'text',
'page': title}
response = requests.get(cls.api_endpoint, params=req_params)
json_response = response.json()
if "error" in json_response:
print(json_response)
raise MissingArticleError(str(json_response["error"]["info"]))
else:
try:
# limit the output, cause sometimes it is obnoxious
contents = json_response['parse']['text']['*'][:1000]
return contents
except KeyError:
raise ParseError(json_response)