Quellcode durchsuchen

towards the xml parser

Martin vor 7 Jahren
Ursprung
Commit
e1fb9419c4
1 geänderte Dateien mit 121 neuen und 9 gelöschten Zeilen
  1. 121 9
      main.py

+ 121 - 9
main.py

@@ -3,6 +3,28 @@ import re
 import os
 import sys
 import xml.etree.ElementTree
+import requests
+
+_HTML_HEAD = '''
+<head>
+    <style>
+        .img-container {
+            width: 400px;
+            padding: 5px;
+            margin: auto;
+        }
+        .wrapper {
+            width: 800px;
+            margin: auto;
+        }
+        img {
+            display: block;
+            max-width: 100%;
+            height: auto;
+        }
+    </style>
+</head>
+'''
 
 def mkdir(dest_path):
     if os.path.exists(dest_path):
@@ -23,8 +45,8 @@ def _comment(node):
             node.find(r'{http://wordpress.org/export/1.2/}comment_author').text,
             node.find(r'{http://wordpress.org/export/1.2/}comment_author_email').text
         ),
-        'date': node.find(r'{http://wordpress.org/export/1.2/}comment_date').text,
-        # 'content': node.find(r'{http://wordpress.org/export/1.2/}comment_content').text
+        'date': node.find(r'{http://wordpress.org/export/1.2/}comment_date').text or '',
+        'content': node.find(r'{http://wordpress.org/export/1.2/}comment_content').text or ''
     }
 
 def _item(node):
@@ -35,21 +57,44 @@ def _item(node):
         'link': node.find(r'link').text,
         'title': node.find(r'title').text,
         'content_html': node.find(r'{http://purl.org/rss/1.0/modules/content/}encoded').text,
+        'post_id': node.find(r'{http://wordpress.org/export/1.2/}post_id').text,
     }
 
     data['id'] = hashlib.md5(data['link'].encode('utf-8')).hexdigest()
 
-    # if data['type'] == 'post':
-    #     for child in node:
-    #         print(child.tag)
-    
     if data['type'] == 'post':
         data['comments'] = [_comment(node) for node in node.findall(r'{http://wordpress.org/export/1.2/}comment')]
+        data['comments'] = [comment for comment in data['comments'] if comment]
+    elif data['type'] == 'attachment':
+        data['attachment'] = node.find(r'{http://wordpress.org/export/1.2/}attachment_url').text
 
     return data
 
+def _download(dest_path, url):
+    print('Downloading %s...' % url)
+
+    extension = url.split('.')[-1]
+    url_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
+    dest_fname = '%s.%s' % (url_hash, extension)
+    dest = os.path.join(dest_path, 'posts', 'files', dest_fname)
+
+    if os.path.exists(dest):
+        print('already exists.')
+        return dest_fname
+
+    # return dest_fname
+
+    resp = requests.get(url)
+    with open(dest, 'wb') as f:
+        f.write(resp.content)
+
+    return dest_fname
+
 def _write_files(dest_path, posts):
     with open(os.path.join(dest_path, 'index.html'), 'w') as f:
+        f.write('<html>\n')
+        f.write(_HTML_HEAD)
+        f.write('<body>')
         f.write('<table>')
         for post in posts:
             f.write('<tr>')
@@ -57,15 +102,32 @@ def _write_files(dest_path, posts):
             f.write('  <td><a href="posts/%s.html">%s</a></td>\n' % (post['id'], post['title']))
             f.write('</tr>\n')
         f.write('</table>')
+        f.write('</body></html>')
 
     for post in posts:
         with open(os.path.join(dest_path, 'posts', '%s.html' % post['id']), 'w') as f:
+            f.write('<html>\n')
+            f.write(_HTML_HEAD)
+            f.write('<body>')
+            f.write('<a href="../index.html">&lt;--- tillbaka</a><hr>')
+            f.write('<div class="wrapper">')
             f.write('<h1>%s: %s</h1>\n' % (post['date'], post['title']))
             f.write(post['content_html'] or '')
 
+            if post['comments']:
+                f.write('<hr>')
+                f.write('<h1>Kommentarer</h1>')
+                for comment in post['comments']:
+                    f.write('<h2>%s: %s</h2>' % (comment['date'], comment['author']))
+                    f.write(comment['content'].replace('\n', '\n<br>'))
+
+            f.write('</div>')
+            f.write('</body></html>')
+
 
 def main(dest_path, xml_files):
     posts = []
+    attachments = {}
 
     for xml_file in xml_files:
         # print('parsing %s...' % xml_file)
@@ -78,19 +140,69 @@ def main(dest_path, xml_files):
 
                 data = _item(item)
 
-                if data['status'] != 'publish' or data['type'] != 'post':
+
+
+                if data['status'] not in ['publish', 'inherit']:
                     continue
 
-                posts.append(data)
+                if data['type'] == 'post':
+                    posts.append(data)
+                elif data['type'] == 'attachment':
+                    attachments[data['post_id']] = data
 
     posts.sort(key=lambda x: x['date'])
 
+    posts = [p for p in posts if p['id'] == '2481127cff605a6239722c80efd67f3c']
+
+    p1 = re.compile(r'(\[caption.*?\])?<a href="(http[^>]*?)"><img[^>]*? src="(http[^>]*?)"[^>]*?></a>([^<]*?\[/caption\])?')
+    p3 = re.compile(r'(\[caption.*?\])?<img[^>]*? src="(http[^>]*?)"[^>]*?>([^<]*?\[/caption\])?')
+    p4 = re.compile(r'\[gallery ids="(.*)"\]')
+
+    drop_patterns = {
+        # re.compile(r'\[gallery ids.*?\]'),
+    }
+
     for post in posts:
+        for p in drop_patterns:
+            for match in re.finditer(p, post['content_html']):
+                post['content_html'] = post['content_html'].replace(match.group(0), '')
+
         if re.match(r'^20\d\d - ', str(post['title'])):
             post['date'] = post['title'][:4]
             post['title'] = post['title'][7:]
 
-        print(post)
+        for match in re.finditer(p1, post['content_html']):
+            caption = match.group(4).replace('[/caption]','').strip() if match.group(4) else ''
+            img_url = match.group(3).split('?')[0]
+            target_url = match.group(2)
+            img_fname = _download(dest_path, img_url)
+            target_fname = _download(dest_path, target_url)
+            img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (target_fname, img_fname, caption)
+            post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
+
+        for match in re.finditer(p3, post['content_html']):
+            img_url = match.group(2).split('?')[0]
+            caption = match.group(3).replace('[/caption]','').strip() if match.group(3) else ''
+            img_fname = _download(dest_path, img_url)
+            img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (img_fname, img_fname, caption)
+            post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
+
+        for match in re.finditer(p4, post['content_html']):
+            ids = match.group(1).split(',')
+            body = []
+            for attachment_id in ids:
+                attachment = attachments.get(attachment_id)
+                if not attachment:
+                    print('could not find attachment %s' % attachment_id)
+                    continue
+                img_url = attachment['attachment']
+                img_fname = _download(dest_path, img_url)
+                body.append('<div class="img-container"><a href="files/%s"><img src="files/%s"></a></div>' % (img_fname, img_fname))
+
+            post['content_html'] = post['content_html'].replace(match.group(0), '\n'.join(body))
+
+
+            print(ids)
 
     _write_files(dest_path, posts)