Advertisement
nicuf

generate sitemap xml from files

Feb 16th, 2022
1,397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. Explanation:
  2.  
  3. ENGLISH: https://neculaifantanaru.com/en/how-to-generate-sitemaps-xml-using-python-and-html-files.html
  4. -----------------
  5.  
  6. import os
  7. import re
  8. import random
  9. import unidecode
  10.  
  11.  
  12. def read_text_from_file(file_path):
  13.     """
  14.    Aceasta functie returneaza continutul unui fisier.
  15.    file_path: calea catre fisierul din care vrei sa citesti
  16.    """
  17.     with open(file_path, encoding='utf8') as f:
  18.         text = f.read()
  19.         return text
  20.  
  21.  
  22. def write_to_file(text, file_path):
  23.     """
  24.    Aceasta functie scrie un text intr-un fisier.
  25.    text: textul pe care vrei sa il scrii
  26.    file_path: calea catre fisierul in care vrei sa scrii
  27.    """
  28.     with open(file_path, 'wb') as f:
  29.         f.write(text.encode('utf8', 'ignore'))
  30.  
  31. def creeaza_fisier_xml():
  32.     lista_nume_fisiere = preia_nume_fisiere_html(
  33.         'e:\\YOUR-FOLDER-WITH-HTML-FILES',
  34.         # files to ignore
  35.         ['404-1.html', '404-2.html', '404-3.html']
  36.     )
  37.     start_xml = read_text_from_file('start_xml.txt')
  38.     final_xml = read_text_from_file('final_xml.txt')
  39.     model_xml = read_text_from_file('model_xml.txt')
  40.  
  41.     xml_text = start_xml + '\n'
  42.     link_pattern = re.compile('<loc>(.*?)</loc>')
  43.     link = re.findall(link_pattern, model_xml)
  44.     if len(link) != 0:
  45.         link = link[0]
  46.  
  47.     for nume_fisier in lista_nume_fisiere:
  48.         model = model_xml
  49.         model = model.replace(link, 'https://YOUR-WEBSITE.com/' + nume_fisier)
  50.         xml_text = xml_text + model + '\n'
  51.  
  52.     xml_text = xml_text + final_xml
  53.  
  54.     write_to_file(xml_text, 'rss.xml')
  55.     print("Scriere efectuata cu succes.")
  56.  
  57. def preia_nume_fisiere_html(folder_fisiere_html, lista_fisiere_de_ignorat):
  58.     lista_nume_fisiere_html = list()
  59.     for f in os.listdir(folder_fisiere_html):
  60.             if f.endswith('.html'):
  61.                 lista_nume_fisiere_html.append(f)
  62.     lista_finala = list()
  63.     for f in lista_nume_fisiere_html:
  64.         if f not in lista_fisiere_de_ignorat:
  65.             lista_finala.append(f)
  66.     return lista_finala
  67.  
  68. def main():
  69.     creeaza_fisier_xml()
  70.  
  71. if __name__ == '__main__':
  72.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement