function to extract annotations from html
[librarian.git] / librarian / html.py
index 1f0615f..1c141f3 100644 (file)
@@ -127,7 +127,13 @@ def extract_fragments(input_filename):
     open_fragments = {}
     closed_fragments = {}
 
-    for event, element in etree.iterparse(input_filename, events=('start', 'end')):
+    # iterparse would die on a HTML document
+    parser = etree.HTMLParser(encoding='utf-8')
+    buf = cStringIO.StringIO()
+    buf.write(etree.tostring(etree.parse(input_filename, parser).getroot()[0][0], encoding='utf-8'))
+    buf.seek(0)
+
+    for event, element in etree.iterparse(buf, events=('start', 'end')):
         # Process begin and end elements
         if element.get('class', '') in ('theme-begin', 'theme-end'):
             if not event == 'end': continue # Process elements only once, on end event
@@ -257,3 +263,15 @@ def add_table_of_contents(root):
 
     root.insert(0, toc)
 
+
+def extract_annotations(html_path):
+    """For each annotation, yields a tuple: anchor, text, html."""
+    parser = etree.HTMLParser(encoding='utf-8')
+    tree = etree.parse(html_path, parser)
+    for footnote in tree.find('//*[@id="footnotes"]').findall('div'):
+        anchor = footnote.find('a[@href]').get('href')
+        del footnote[:2]
+        text_str = etree.tostring(footnote, method='text', encoding='utf-8')
+        html_str = etree.tostring(footnote, method='html', encoding='utf-8')
+        yield anchor, text_str, html_str
+