Skip to content

Instantly share code, notes, and snippets.

@muhiminulhasan
Created June 1, 2024 23:31
Show Gist options
  • Select an option

  • Save muhiminulhasan/63a6efa5486f7958aa39c60195c2c098 to your computer and use it in GitHub Desktop.

Select an option

Save muhiminulhasan/63a6efa5486f7958aa39c60195c2c098 to your computer and use it in GitHub Desktop.
This Python script generates a Blogger backup XML file from a collection of HTML files in a specified directory.
import os
import glob
import datetime
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
# Define the directory containing the HTML files
html_dir = "posts"
ns = {
'atom': "http://www.w3.org/2005/Atom",
}
feed = Element('feed', xmlns=ns['atom'])
generator = SubElement(feed, 'generator')
generator.text = 'Blogger'
updated = SubElement(feed, 'updated')
updated.text = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
for i, html_file in enumerate(glob.glob(os.path.join(html_dir, '*.html')), start=1):
with open(html_file, 'r', encoding='utf-8') as file:
content = file.read()
file_name = os.path.splitext(os.path.basename(html_file))[0]
entry = SubElement(feed, 'entry')
category1 = SubElement(entry, 'category', scheme="http://www.blogger.com/atom/ns#", term="recipe")
category2 = SubElement(entry, 'category', scheme="http://schemas.google.com/g/2005#kind", term="http://schemas.google.com/blogger/2008/kind#post")
post_id = SubElement(entry, 'id')
post_id.text = f'post-{i}'
author = SubElement(entry, 'author')
name = SubElement(author, 'name')
name.text = 'Book'
content_element = SubElement(entry, 'content', type="html")
content_element.text = content
published = SubElement(entry, 'published')
published.text = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
title = SubElement(entry, 'title', type="html")
title.text = file_name
tree = ElementTree(feed)
with open('blogspot_backup.xml', 'wb') as xml_file:
tree.write(xml_file, encoding='utf-8', xml_declaration=True)
print("Blogger backup XML created successfully.")
<?xml version='1.0' encoding='UTF-8'?>
<ns0:feed
xmlns:ns0="http://www.w3.org/2005/Atom">
<ns0:generator>Blogger</ns0:generator>
<ns0:updated>2024-05-30T10:25:17Z</ns0:updated>
<ns0:entry>
<ns0:category scheme="http://www.blogger.com/atom/ns#" term="recipe" />
<ns0:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/blogger/2008/kind#post" />
<ns0:id>post-10</ns0:id>
<ns0:author>
<ns0:name>Book</ns0:name>
</ns0:author>
<ns0:content type="html">Test content</ns0:content>
<ns0:published>2024-05-23T21:42:16Z</ns0:published>
<ns0:title type="html">Hello</ns0:title>
</ns0:entry>
</ns0:feed>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment