/
speedparser.py
643 lines (555 loc) · 23.5 KB
/
speedparser.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""An attempt to be able to parse 80% of feeds that feedparser would parse
in about 1% of the time feedparser would parse them in.
LIMITATIONS:
* result.feed.namespaces will only contain namespaces declaed on the
root object, not those declared later in the file
* general lack of support for many types of feeds
* only things verified in test.py are guaranteed to be there; many fields
which were not considered important were skipped
"""
import re
import os
import sys
import time
import chardet
from lxml import etree, html
from lxml.html import clean
try:
import feedparser
except:
import feedparsercompat as feedparser
keymap = feedparser.FeedParserDict.keymap
fpnamespaces = feedparser._FeedParserMixin.namespaces
xmlns_map = {
'http://www.w3.org/2005/atom': 'atom10',
'http://purl.org/rss/1.0/': 'rss10',
'http://my.netscape.com/rdf/simple/0.9/': 'rss090',
}
default_cleaner = clean.Cleaner(comments=True, javascript=True,
scripts=True, safe_attrs_only=True, page_structure=True,
style=True)
simple_cleaner = clean.Cleaner(safe_attrs_only=True, page_structure=True)
class FakeCleaner(object):
def clean_html(self, x): return x
class IncompatibleFeedError(Exception):
pass
fake_cleaner = FakeCleaner()
# --- text utilities ---
def unicoder(txt, hint=None, strip=True):
if txt is None:
return None
if strip:
txt = txt.strip()
if hint:
try: return txt.decode(hint)
except: return unicoder(txt)
try:
return txt.decode('utf-8')
except:
try: return txt.decode('latin-1')
except:
try: return txt.decode('iso-8859')
except: return txt
def first_text(xpath_result, default='', encoding='utf-8'):
if xpath_result:
return unicoder(xpath_result[0].text, encoding) or default
return default
def strip_outer_tag(text):
"""Strips the outer tag, if text starts with a tag. Not entity aware;
designed to quickly strip outer tags from lxml cleaner output. Only
checks for <p> and <div> outer tags."""
if not text or not isinstance(text, basestring):
return text
stripped = text.strip()
if (stripped.startswith('<p>') or stripped.startswith('<div>')) and \
(stripped.endswith('</p>') or stripped.endswith('</div>')):
return stripped[stripped.index('>')+1:stripped.rindex('<')]
return text
nsre = re.compile(r'xmlns\s*=\s*[\'"](.+?)[\'"]')
def strip_namespace(document):
if document[:1000].count('xmlns') > 5:
if 'xmlns' not in document[:1000]:
return None, document
elif 'xmlns' not in document[:400]:
return None, document
match = nsre.search(document)
if match:
return match.groups()[0], nsre.sub('', document)
return None, document
def munge_author(author):
"""If an author contains an email and a name in it, make sure it is in
the format: "name (email)"."""
# this loveliness is from feedparser but was not usable as a function
if '@' in author:
emailmatch = re.search(ur'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author)
if emailmatch:
email = emailmatch.group(0)
# probably a better way to do the following, but it passes all the tests
author = author.replace(email, u'')
author = author.replace(u'()', u'')
author = author.replace(u'<>', u'')
author = author.replace(u'<>', u'')
author = author.strip()
if author and (author[0] == u'('):
author = author[1:]
if author and (author[-1] == u')'):
author = author[:-1]
author = author.strip()
return '%s (%s)' % (author, email)
return author
# --- common xml utilities ---
def reverse_namespace_map(nsmap):
d = fpnamespaces.copy()
d.update(dict([(v,k) for (k,v) in nsmap.iteritems()]))
return d
def base_url(root):
"""Determine the base url for a root element."""
for attr,value in root.attrib.iteritems():
if attr.endswith('base') and 'http' in value:
return value
return None
def full_href(href, base=None):
if base is None:
return href
if href.startswith('javascript:'):
return href
if 'http://' in href or 'https://' in href:
return href
return '%s/%s' % (base.rstrip('/'), href.lstrip('/'))
def full_href_attribs(attribs, base=None):
if base is None: return dict(attribs)
d = dict(attribs)
for key,value in d.iteritems():
if key == 'href':
d[key] = full_href(value, base)
return d
def clean_ns(tag):
"""Return a tag and its namespace separately."""
if '}' in tag:
split = tag.split('}')
return split[0].strip('{'), split[-1]
return '', tag
def xpath(node, query, namespaces={}):
"""A safe xpath that only uses namespaces if available."""
if namespaces and 'None' not in namespaces:
return node.xpath(query, namespaces=namespaces)
return node.xpath(query)
def innertext(node):
"""Return the inner text of a node. If a node has no sub elements, this
is just node.text. Otherwise, it's node.text + sub-element-text +
node.tail."""
if not len(node): return node.text
return (node.text or '') + ''.join([etree.tostring(c) for c in node]) + (node.tail or '')
class SpeedParserEntriesRss20(object):
entry_xpath = '/rss/item | /rss/channel/item'
tag_map = {
'pubDate' : 'date',
'pubdate' : 'date',
'date': 'date',
'updated' : 'date',
'modified' : 'date',
'link' : 'links',
'title': 'title',
'creator': 'author',
'author': 'author',
'name': 'author',
'guid': 'guid',
'id': 'guid',
'comments': 'comments',
'encoded': 'content',
'content': 'content',
'summary': 'summary',
'description': 'summary',
'media:content': 'media_content',
'media:thumbnail': 'media_thumbnail',
'media_thumbnail': 'media_thumbnail',
'media:group': 'media_group',
'itunes:summary': 'content',
'gr:annotation': 'annotation',
}
def __init__(self, root, namespaces={}, version='rss20', encoding='utf-8', feed={},
cleaner=default_cleaner, unix_timestamp=False):
self.encoding = encoding
self.namespaces = namespaces
self.unix_timestamp = unix_timestamp
self.nslookup = reverse_namespace_map(namespaces)
self.cleaner = cleaner
self.entry_objects = xpath(root, self.entry_xpath, namespaces)
self.feed = feed
self.baseurl = base_url(root)
if not self.baseurl and 'link' in self.feed:
self.baseurl = self.feed.link
entries = []
for obj in self.entry_objects:
d = self.parse_entry(obj)
if d: entries.append(d)
self.entries = entries
def clean(self, text):
if text and isinstance(text, basestring):
return self.cleaner.clean_html(text)
return text
def parse_entry(self, entry):
"""An attempt to parse pieces of an entry out w/o xpath, by looping
over the entry root's children and slotting them into the right places.
This is going to be way messier than SpeedParserEntries, and maybe
less cleanly usable, but it should be faster."""
e = feedparser.FeedParserDict()
tag_map = self.tag_map
nslookup = self.nslookup
for child in entry.getchildren():
if isinstance(child, etree._Comment):
continue
ns, tag = clean_ns(child.tag)
mapping = tag_map.get(tag, None)
if mapping:
getattr(self, 'parse_%s' % mapping)(child, e, nslookup.get(ns, ns))
if not ns:
continue
fulltag = '%s:%s' % (nslookup.get(ns, ''), tag)
mapping = tag_map.get(fulltag, None)
if mapping:
getattr(self, 'parse_%s' % mapping)(child, e, nslookup[ns])
lacks_summary = 'summary' not in e or e['summary'] is None
lacks_content = 'content' not in e or not bool(e.get('content', None))
if not lacks_summary and lacks_content:
e['content'] = [{'value': e.summary}]
# feedparser sometimes copies the first content value into the
# summary field when summary was completely missing; we want
# to do that as well, but avoid the case where summary was given as ''
if lacks_summary and not lacks_content:
e['summary'] = e['content'][0]['value']
if e.get('summary', False) is None:
e['summary'] = u''
# support feed entries that have a guid but no link
if 'guid' in e and 'link' not in e:
e['link'] = full_href(e['guid'], self.baseurl)
return e
def parse_date(self, node, entry, ns=''):
value = unicoder(node.text)
entry['updated'] = value
date = feedparser._parse_date(value)
if self.unix_timestamp and date:
date = time.mktime(date)
entry['updated_parsed'] = date
def parse_title(self, node, entry, ns=''):
if ns in ('media',) and 'title' in entry:
return
title = unicoder(node.text).strip() or ''
title = strip_outer_tag(self.clean(title))
entry['title'] = title or ''
def parse_author(self, node, entry, ns=''):
if ns and ns in ('itunes', 'dm') and 'author' in entry:
return
if node.text and len(list(node)) == 0:
entry['author'] = munge_author(unicoder(node.text))
return
name, email = None, None
for child in node:
if child.tag == 'name': name = unicoder(child.text or '')
if child.tag == 'email': email = unicoder(child.text or '')
if name and not email:
entry['author'] = munge_author(name)
elif not name and not email:
entry['author'] = ''
else:
entry['author'] = '%s (%s)' % (name, email)
def parse_guid(self, node, entry, ns=''):
entry['guid'] = unicoder(node.text)
def parse_annotation(self, node, entry, ns='gr'):
if entry.get('author', '') and 'unknown' not in entry['author'].lower():
return
for child in node:
if child.tag.endswith('author'):
self.parse_author(child, entry, ns='')
def parse_links(self, node, entry, ns=''):
if unicoder(node.text):
entry['link'] = full_href(unicoder(node.text).strip('#'), self.baseurl)
if 'link' not in entry and node.attrib.get('rel', '') == 'alternate' and 'href' in node.attrib:
entry['link'] = full_href(unicoder(node.attrib['href']).strip('#'), self.baseurl)
if 'link' not in entry and 'rel' not in node.attrib and 'href' in node.attrib:
entry['link'] = full_href(unicoder(node.attrib['href']).strip('#'), self.baseurl)
entry.setdefault('links', []).append(full_href_attribs(node.attrib, self.baseurl))
# media can be embedded within links..
for child in node:
ns, tag = clean_ns(child.tag)
if self.nslookup[ns] == 'media' and tag == 'content':
self.parse_media_content(child, entry)
def parse_comments(self, node, entry, ns=''):
if 'comments' in entry and ns: return
entry['comments'] = strip_outer_tag(self.clean(unicoder(node.text)))
def parse_content(self, node, entry, ns=''):
# media:content is processed as media_content below
if ns and node.tag.endswith('content') and ns not in ('itunes',):
return
content = unicoder(innertext(node))
content = self.clean(content)
entry.setdefault('content', []).append({'value': content or ''})
def parse_summary(self, node, entry, ns=''):
if ns in ('media', ): return
if ns == 'itunes' and entry.get('summary', None):
return
if 'content' in entry:
entry['summary'] = entry['content'][0]['value']
return
summary = unicoder(innertext(node))
summary = self.clean(summary)
entry['summary'] = summary or ''
def parse_media_content(self, node, entry, ns='media'):
entry.setdefault('media_content', []).append(dict(node.attrib))
for child in node:
if child.tag.endswith('thumbnail'):
entry.setdefault('media_thumbnail', []).append(dict(child.attrib))
def parse_media_thumbnail(self, node, entry, ns='media'):
entry.setdefault('media_thumbnail', []).append(dict(node.attrib))
def parse_media_group(self, node, entry, ns='media'):
for child in node:
if child.tag.endswith('content'):
self.parse_media_content(child, entry)
elif child.tag.endswith('thumbnail'):
self.parse_media_thumbnail(child, entry)
def entry_list(self):
return self.entries
class SpeedParserEntriesRdf(SpeedParserEntriesRss20):
entry_xpath = '/rdf:RDF/item | /rdf:RDF/channel/item'
class SpeedParserEntriesAtom(SpeedParserEntriesRss20):
entry_xpath = '/feed/entry'
def parse_summary(self, node, entry, ns=''):
if 'content' in entry:
entry['summary'] = entry['content'][0]['value']
else:
super(SpeedParserEntriesAtom, self).parse_summary(node, entry, ns)
class SpeedParserFeedRss20(object):
channel_xpath = '/rss/channel'
tag_map = {
'title' : 'title',
'description' : 'subtitle',
'tagline' : 'subtitle',
'subtitle' : 'subtitle',
'link' : 'links',
'pubDate': 'date',
'updated' : 'date',
'modified' : 'date',
'date': 'date',
'generator' : 'generator',
'generatorAgent': 'generator',
'language' : 'lang',
'id': 'id',
'lastBuildDate' : 'date',
}
def __init__(self, root, namespaces={}, encoding='utf-8', type='rss20', cleaner=default_cleaner,
unix_timestamp=False):
"""A port of SpeedParserFeed that uses far fewer xpath lookups, which
ends up simplifying parsing and makes it easier to catch the various
names that different tags might come under."""
self.root = root
self.unix_timestamp = unix_timestamp
nslookup = reverse_namespace_map(namespaces)
self.cleaner = cleaner
self.baseurl = base_url(root)
feed = feedparser.FeedParserDict()
tag_map = self.tag_map
channel = xpath(root, self.channel_xpath, namespaces)
if len(channel) == 1:
channel = channel[0]
for child in channel:
if isinstance(child, etree._Comment):
continue
ns, tag = clean_ns(child.tag)
mapping = tag_map.get(tag, None)
if mapping:
getattr(self, 'parse_%s' % mapping)(child, feed, nslookup.get(ns, ns))
if not ns:
continue
fulltag = '%s:%s' % (nslookup.get(ns, ''), tag)
mapping = tag_map.get(fulltag, None)
if mapping:
getattr(self, 'parse_%s' % mapping)(child, feed, nslookup[ns])
# this copies feedparser behavior if, say, xml:lang is defined in the
# root feed element, even though this element tends to have garbage like
# "utf-8" in it rather than an actual language
if 'language' not in feed:
for attr in root.attrib:
if attr.endswith('lang'):
feed['language'] = root.attrib[attr]
if 'id' in feed and 'link' not in feed:
feed['link'] = feed['id']
self.feed = feed
def clean(self, text, outer_tag=True):
if text and isinstance(text, basestring):
if not outer_tag:
txt = self.cleaner.clean_html(text)
frag = lxml.html.fragment_fromstring(txt)
return self.cleaner.clean_html(text)
return text
def parse_title(self, node, feed, ns=''):
feed['title'] = strip_outer_tag(self.clean(unicoder(node.text))) or ''
def parse_subtitle(self, node, feed, ns=''):
feed['subtitle'] = strip_outer_tag(self.clean(unicoder(node.text))) or ''
def parse_links(self, node, feed, ns=''):
if node.text:
feed['link'] = full_href(unicoder(node.text).strip('#'), self.baseurl)
if 'link' not in feed and node.attrib.get('rel', '') == 'alternate' and 'href' in node.attrib:
feed['link'] = full_href(unicoder(node.attrib['href']).strip('#'), self.baseurl)
if 'link' not in feed and 'rel' not in node.attrib and 'href' in node.attrib:
feed['link'] = full_href(unicoder(node.attrib['href']).strip('#'), self.baseurl)
feed.setdefault('links', []).append(full_href_attribs(node.attrib, self.baseurl))
def parse_date(self, node, feed, ns=''):
value = unicoder(node.text)
feed['updated'] = value
date = feedparser._parse_date(value)
if self.unix_timestamp and date:
date = time.mktime(date)
feed['updated_parsed'] = date
def parse_lang(self, node, feed, ns=''):
feed['language'] = unicoder(node.text)
def parse_generator(self, node, feed, ns=''):
value = unicoder(node.text)
if value:
feed['generator'] = value
else:
for value in node.attrib.itervalues():
if 'http://' in value:
feed['generator'] = value
def parse_id(self, node, feed, ns=''):
feed['id'] = unicoder(node.text)
def feed_dict(self):
return self.feed
class SpeedParserFeedAtom(SpeedParserFeedRss20):
channel_xpath = '/feed'
class SpeedParserFeedRdf(SpeedParserFeedRss20):
channel_xpath = '/rdf:RDF/channel'
class SpeedParser(object):
version_map = {
'rss2': 'rss20',
}
def __init__(self, content, cleaner=default_cleaner, unix_timestamp=False, encoding=None):
self.cleaner = cleaner
self.xmlns, content = strip_namespace(content)
self.unix_timestamp = unix_timestamp
if self.xmlns and '#' in self.xmlns:
self.xmlns = self.xmlns.strip('#')
parser = etree.XMLParser(recover=True)
tree = etree.fromstring(content, parser=parser)
if isinstance(tree, etree._ElementTree):
self.tree = tree
self.root = tree.getroot()
else:
self.tree = tree.getroottree()
self.root = tree
self.encoding = encoding if encoding else self.parse_encoding()
self.version = self.parse_version()
if self.version in self.version_map:
self.version = self.version_map[self.version]
if 'unk' in self.version:
raise IncompatibleFeedError("Could not determine version of this feed.")
self.namespaces = self.parse_namespaces()
self.feed = self.parse_feed(self.version, self.encoding)
self.entries = self.parse_entries(self.version, self.encoding)
def parse_version(self):
r = self.root
root_ns, root_tag = clean_ns(r.tag)
root_tag = root_tag.lower()
vers = 'unk'
if self.xmlns and self.xmlns.lower() in xmlns_map:
value = xmlns_map[self.xmlns.lower()]
if value == 'rss10' and root_tag == 'rss':
value = 'rss010'
if not (value.startswith('atom') and root_tag == 'rss'):
return value
elif self.xmlns:
vers = self.xmlns.split('/')[-2].replace('.', '')
tag = root_tag
if r.attrib.get('version', None):
vers = r.attrib['version'].replace('.', '')
if root_tag in ('rss', 'rdf'):
tag = 'rss'
if root_tag in ('feed'):
tag = 'atom'
if root_tag == 'rss' and vers == '10' and root_tag == 'rss':
vers = ''
return '%s%s' % (tag, vers)
def parse_namespaces(self):
nsmap = self.root.nsmap.copy()
for key in nsmap.keys():
if key is None:
nsmap[self.xmlns] = nsmap[key]
del nsmap[key]
break
return nsmap
def parse_encoding(self):
return self.tree.docinfo.encoding.lower()
def parse_feed(self, version, encoding):
kwargs = dict(
encoding=encoding,
unix_timestamp=self.unix_timestamp,
namespaces=self.namespaces
)
if version in ('rss20', 'rss092', 'rss091', 'rss'):
return SpeedParserFeedRss20(self.root, **kwargs).feed_dict()
if version in ('rss090', 'rss10'):
return SpeedParserFeedRdf(self.root, **kwargs).feed_dict()
if version in ('atom10', 'atom03'):
return SpeedParserFeedAtom(self.root, **kwargs).feed_dict()
raise IncompatibleFeedError("Feed not compatible with speedparser.")
def parse_entries(self, version, encoding):
kwargs = dict(encoding=encoding, namespaces=self.namespaces,
cleaner=self.cleaner, feed=self.feed, unix_timestamp=self.unix_timestamp)
if version in ('rss20', 'rss092', 'rss091', 'rss'):
return SpeedParserEntriesRss20(self.root, **kwargs).entry_list()
if version in ('rss090', 'rss10'):
return SpeedParserEntriesRdf(self.root, **kwargs).entry_list()
if version in ('atom10', 'atom03'):
return SpeedParserEntriesAtom(self.root, **kwargs).entry_list()
raise IncompatibleFeedError("Feed not compatible with speedparser.")
def update(self, result):
if self.version:
result['version'] = self.version
if self.namespaces:
result['namespaces'] = self.namespaces
if self.feed:
result.feed.update(self.feed)
if self.entries:
result['entries'] = self.entries
if self.encoding:
result['encoding'] = self.encoding
def parse(document, clean_html=True, unix_timestamp=False, encoding=None):
"""Parse a document and return a feedparser dictionary with attr key access.
If clean_html is False, the html in the feed will not be cleaned. If
clean_html is True, a sane version of lxml.html.clean.Cleaner will be used.
If it is a Cleaner object, that cleaner will be used. If unix_timestamp is
True, the date information will be a numerical unix timestamp rather than a
struct_time. If encoding is provided, the encoding of the document will be
manually set to that."""
if isinstance(clean_html, bool):
cleaner = default_cleaner if clean_html else fake_cleaner
else:
cleaner = clean_html
result = feedparser.FeedParserDict()
result['feed'] = feedparser.FeedParserDict()
result['entries'] = []
result['bozo'] = 0
try:
parser = SpeedParser(document, cleaner, unix_timestamp, encoding)
parser.update(result)
except Exception, e:
if isinstance(e, UnicodeDecodeError) and encoding is True:
encoding = chardet.detect(document)['encoding']
document = document.decode(encoding, 'replace').encode('utf-8')
return parse(document, clean_html, unix_timestamp, encoding)
import traceback
result['bozo'] = 1
result['bozo_exception'] = e
result['bozo_tb'] = traceback.format_exc()
return result
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print "Must provide filename of feed."
filename = sys.argv[1]
feed = open(filename).read()
if '-- END TRACEBACK --' in feed:
feed = feed.split('-- END TRACEBACK --')[1].strip()
import pprint
pprint.pprint(parse(feed))