Blog Spot

Programa que permite una conversión del BlogSpot ( en su extracción XML ) a formato PMWiki

  1. from lxml import etree
  2. from datetime import datetime
  3. from dateutil import parser
  4. import copy
  5. import re
  6. import os
  7. import requests
  8. from bs4 import BeautifulSoup
  9.  
  10. def get_all_images(p_html):
  11.     if '<img' in p_html:
  12.         soup = BeautifulSoup(p_html, "html.parser")
  13.  
  14.         # Crear carpeta para almacenar imágenes
  15.         os.makedirs("imagenes", exist_ok=True)
  16.  
  17.         # Buscar todas las etiquetas <img>
  18.         for img_tag in soup.find_all("img"):
  19.             img_url = img_tag.get("src")
  20.             file_name = os.path.basename(img_url)
  21.             if not os.path.exists('imagenes/'+file_name):
  22.                 if img_url and 'bergonzini' not in img_url and 'espacioblog' not in img_url \
  23.                    and 'windsor' not in img_url:
  24.                     # Obtener el nombre del archivo
  25.                     img_name = os.path.basename(img_url)
  26.                     img_path = os.path.join("imagenes", img_name)
  27.  
  28.                     # Descargar la imagen
  29.                     try:
  30.                         response = requests.get(img_url)  
  31.                     except:
  32.                         with open(img_path, "w") as file:
  33.                             file.write('error')                            
  34.                     else:
  35.                         if response.status_code == 200:
  36.                             with open(img_path, "wb") as file:
  37.                                 file.write(response.content)  
  38.                         else:
  39.                             with open(img_path, "w") as file:
  40.                                 file.write('error')  
  41.  
  42.  
  43.  
  44. def sanitizar(p_str):
  45.     if p_str in (None, ''):
  46.         return p_str
  47.     else:    
  48.         cx = p_str  
  49.         cx = cx.replace('</p>',"")
  50.         cx = cx.replace('
  51.  
  52. ',r'%0a')
  53.         cx = cx.replace('\\
  54. ',r'%0a')
  55.         cx = cx.replace('\\
  56. ',r'%0a')
  57.         cx = cx.replace('
  58.  
  59. ! ','!')    
  60.         cx = cx.replace('<h2>','!!')
  61.         cx = cx.replace('<h3>','!!!')
  62.         cx = cx.replace('<h4>','!!!!')  
  63.         cx = cx.replace('
  64. ','')    
  65.         cx = cx.replace('</div>','')  
  66.         cx = cx.replace('</h2>','')
  67.         cx = cx.replace('</h3>','')
  68.         cx = cx.replace('</h4>','')  
  69.         cx = cx.replace('
  70.  
  71. ! ','!')    
  72.         cx = cx.replace('<H2>','!!')
  73.         cx = cx.replace('<H3>','!!!')
  74.         cx = cx.replace('<H4>','!!!!')  
  75.         cx = cx.replace('
  76. ','')    
  77.         cx = cx.replace('</H2>','')
  78.         cx = cx.replace('</H3>','')
  79.         cx = cx.replace('</H4>','')          
  80.         cx = cx.replace(''''',"'''")
  81.        cx = cx.replace(''''',"'''")
  82.        cx = cx.replace(''-',"[- ")        
  83.        cx = cx.replace('-''," -]")                
  84.        cx = cx.replace(''''',"'''")
  85.         cx = cx.replace(''''',"'''")
  86.        cx = cx.replace('''',"''")
  87.        cx = cx.replace('''',"''")        
  88.        cx = cx.replace('''',"''")                
  89.        cx = cx.replace('</span>',"")
  90.        cx = cx.replace('''',"''")  
  91.        cx = cx.replace(';s:8:"category','')
  92.        cx = cx.replace(r'\n',r'%0a')  
  93.  
  94.        pattern = r'<img[^>]*src=["\'](.*?)["\'][^>]*>'
  95.  
  96.         cx = re.sub(pattern, r" %width=50pct%\1 ", cx)  
  97.         #cx = cx.replace('../images/','Path:/uploads/BLOG/')
  98.         cx = re.sub(r'<div[^>]+>','',cx)
  99.         cx = re.sub(r'<span [^>]+>','',cx)
  100.         cx = re.sub(r'<a [^>]*href="([^"]+)"[^>]*>(.*?)</a>', r' [[ 1 | 2 ]] ',cx)
  101.         #pattern = r'<as+href="([^"]+)"[^>]*>(.*?)</a>'
  102.         #cx = re.sub(pattern, r'[[\1|\2]]', cx)
  103.  
  104.         return cx
  105.  
  106. # Cargar el archivo XML
  107. tree = etree.parse('blog-05-12-2025.xml')
  108. datos = []
  109. tmp = {}
  110. data_titulo = ''
  111. data_fecha = ''
  112. # Recorrer los elementos
  113. for elem in tree.iter():
  114.  
  115.     if elem.tag == '{http://www.w3.org/2005/Atom}entry':
  116.  
  117.         for ele in elem:
  118.             if ele.tag == '{http://www.w3.org/2005/Atom}id':
  119.                 if 'post' in ele.text:
  120.                     tmp['id'] = ele.text
  121.                 else:
  122.                     break
  123.             if 'rel' in ele.attrib:
  124.                 if ele.attrib['rel'] == 'alternate':
  125.                     tmp['link'] = ele.attrib['href']
  126.             if ele.tag == '{http://www.w3.org/2005/Atom}published':
  127.                 fecha_objeto = parser.parse(ele.text)
  128.                 tmp['fecha'] = fecha_objeto.strftime("%Y%m%d %H:%M")
  129.                 tmp['fichero'] = fecha_objeto.strftime("%Y%m%d%H%M")
  130.             if ele.tag == '{http://www.w3.org/2005/Atom}content':
  131.                # get_all_images(ele.text)
  132.                 tmp['text'] = sanitizar(ele.text)
  133.  
  134.             if ele.tag == '{http://www.w3.org/2005/Atom}title':
  135.                 tmp['titulo'] = sanitizar(ele.text)
  136.             if ele.tag == '{http://www.w3.org/2005/Atom}author':
  137.                 for el in ele:
  138.                     if el.tag == '{http://www.w3.org/2005/Atom}name':
  139.                         tmp['autor']  = el.text
  140.  
  141.         if tmp:
  142.             if 'link' in tmp:
  143.                 if 'showComment' not in tmp['link']:
  144.                     datos.append(copy.deepcopy(tmp))
  145.             else:
  146.                 datos.append(copy.deepcopy(tmp))
  147.             tmp.clear()
  148.  
  149.  
  150. datos = sorted(datos, key=lambda x: x["fecha"])
  151.  
  152. # Descromprimimos lo leído
  153.  
  154. fmain = open('out/McRatas.BLOG',"w",encoding='utf-8')
  155. fmaind = 'version=pmwiki-2.4.4 ordered=1 urlencoded=1' + os.linesep + \
  156.          'agent=Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:138.0) Gecko/20100101 Firefox/138.0' + os.linesep + \
  157.          'charset=UTF-8' + os.linesep + \
  158.          'name=McRatas.BLOG' + os.linesep + \
  159.          'text=(:title Listado de publicaciones:)' + r'%0a' + r'%0a'
  160.  
  161. for elemento in datos:
  162.     fichero = 'McRatas.BLOG'+elemento['fichero']
  163.     fichero_origen = 'McRatas.BLOG'+elemento['fichero']
  164.     contador = 0
  165.     while os.path.exists('out/'+fichero):
  166.         fichero = fichero_origen + '_' + str(contador)
  167.         contador += 1
  168.  
  169.     fin = open('out/'+fichero,'w', encoding='utf-8')  
  170.     if elemento['titulo'] in ('', None, []):
  171.         elemento['titulo'] = 'Sin título '+ elemento["fecha"]
  172.     if 'link' in elemento:
  173.         if elemento['link'] in ('', None, []):
  174.             elemento['link'] = ''
  175.         else:
  176.             elemento['link'] = 'Enlace: [['+elemento['link']+' | ' + elemento['link']+' ]]'
  177.     else:
  178.         elemento['link'] = ''
  179.     elemento['text'] = elemento['text'] + os.linesep + \
  180.                        '----' + os.linesep + \
  181.                        'Publicado en : ' + elemento['fecha'] + os.linesep + \
  182.                        'Por ' + elemento['autor'] + os.linesep + elemento['link']
  183.  
  184.     elemento["text"] = re.sub(os.linesep,r'%0a',elemento["text"])
  185.     fint = 'version=pmwiki-2.4.4 ordered=1 urlencoded=1' + os.linesep + \
  186.          'agent=Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:138.0) Gecko/20100101 Firefox/138.0' + os.linesep + \
  187.          'charset=UTF-8' + os.linesep + \
  188.          'name=' + fichero + os.linesep + \
  189.          'text=(:title '+ elemento["titulo"]+':)'+elemento["text"]
  190.     fin.write(fint)
  191.     fin.close()
  192.     fmaind = fmaind + '[['+fichero+' | '+ elemento['fecha']+']] '+ elemento["titulo"] + r'%0a'
  193.  
  194. fmain.write(fmaind)    
  195. fmain.close()        
  196.