-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
82 lines (70 loc) · 1.95 KB
/
parser.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
75
76
77
78
79
80
81
82
#!/usr/bin/python
from HTMLParser import HTMLParser
import doctest
def get_href(attrs):
"""Retourne la valeur de l'href
>>> get_href([('href', '/partners/'), ('target', '_blank')])
'/partners/'
>>> get_href([('class', 'color2'), ('href', 'http://bookre.org/reader?file=677155')])
'http://bookre.org/reader?file=677155'
>>> get_href([('href', 'javascript:void(0)'), ('onclick', 'return false')])
'javascript:void(0)'
"""
for attr, value in attrs:
if attr == 'href':
return value
return None
class BookfiParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.in_exact_match = False
self.in_title = False
self.in_author = False
self.div_count = 0
self.title = ""
self.author = ""
self.url = ""
self.results = []
def get_results(self, html):
"""Renvoie les resultats"""
self.title = ""
self.author = ""
self.url = ""
self.results = []
self.feed(html)
return self.results
def handle_starttag(self, tag, attrs):
if ('class', 'resItemBox exactMatch') in attrs:
self.in_exact_match = True
else:
if self.in_exact_match:
if tag == 'a':
if ('title', 'Electronic library download book ') in attrs:
self.url = get_href(attrs)
el = {'title': self.title, 'author': self.author, 'url': self.url}
self.results.append(el)
elif ('title', "Find all the author's book") in attrs:
self.in_author = True
elif tag == 'a':
print attrs
elif tag == 'div':
self.div_count += 1
elif tag == 'h3':
self.in_title = True
def handle_data(self, data):
if self.in_title:
self.title = data
elif self.in_author:
self.author = data
def handle_endtag(self, tag):
if self.in_exact_match and tag == 'div':
if self.div_count == 0:
self.in_exact_match = False
else:
self.div_count -= 1
elif self.in_title and tag == 'h3':
self.in_title = False
elif self.in_author and tag == 'a':
self.in_author = False
if __name__ == '__main__':
doctest.testmod()