-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookextract.py
More file actions
executable file
·76 lines (59 loc) · 1.87 KB
/
bookextract.py
File metadata and controls
executable file
·76 lines (59 loc) · 1.87 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python
from cookielib import CookieJar
import urllib
import urllib2
import sys
import json
import codecs
logonparams = {
'action': 'login',
'lgname': sys.argv[2],
'lgpassword': sys.argv[3],
'format': 'json'
}
pageparams = {
'action': 'parse',
'format': 'json',
'page': sys.argv[1],
'prop': 'text|images|displaytitle|headitems|headhtml',
'contentmodel': 'text'
}
user_agent = 'BookExtractorScript (mwalker@wikimedia.org)'
logonurl = "https://en.wikipedia.org/w/api.php"
pageurl = "https://en.wikipedia.org/w/api.php"
headers = { 'User-Agent' : user_agent }
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# First logon request
req = urllib2.Request(logonurl, urllib.urlencode(logonparams), headers)
response = opener.open(req)
data = json.loads(response.read())
token = data['login']['token']
logonparams['lgtoken'] = token
if data['login']['result'] != "NeedToken":
print("ERROR -- did not get expected result from server whilst logging in")
exit(1)
# Second logon request
req = urllib2.Request(logonurl, urllib.urlencode(logonparams), headers)
response = opener.open(req)
data = json.loads(response.read())
if data['login']['result'] != 'Success':
print("ERROR -- login was not successful! invalid username/password?")
exit(1)
# page request
req = urllib2.Request(pageurl, urllib.urlencode(pageparams), headers)
response = opener.open(req)
data = json.loads(response.read())
# keys here are ['parse'] -> [u'headitems', u'displaytitle', u'title', u'text', u'headhtml', u'images']
of = codecs.open('out.html', 'w', 'utf-8')
of.write(data['parse']['text']['*'])
of.flush()
of.close()
of = codecs.open('headitems.html', 'w', 'utf-8')
of.write(data['parse']['headitems'][0])
of.flush()
of.close()
of = codecs.open('headhtml.html', 'w', 'utf-8')
of.write(data['parse']['headhtml']['*'])
of.flush()
of.close()