欢迎访问宙启技术站
智能推送

使用Python编写自动更新Sitemap并备份的脚本

发布时间:2023-12-11 14:07:48

以下是一个使用Python编写的自动更新Sitemap并备份的脚本,并包含使用例子。

import os
import requests
import datetime
import xml.etree.ElementTree as ET
from shutil import copyfile

# Sitemap URL
SITEMAP_URL = "http://www.example.com/sitemap.xml"

# Backup directory
BACKUP_DIR = "/path/to/backup"

# Function to update the Sitemap
def update_sitemap():
    # Get the current date and time
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y%m%d_%H%M%S")

    # Download the current Sitemap
    response = requests.get(SITEMAP_URL)
    sitemap_content = response.text

    # Save the current Sitemap as a backup
    backup_file = os.path.join(BACKUP_DIR, f"sitemap_backup_{timestamp}.xml")
    with open(backup_file, 'w') as f:
        f.write(sitemap_content)

    # Parse the Sitemap XML
    root = ET.fromstring(sitemap_content)

    # Update the lastmod attribute for each URL
    for url in root.findall("{http://www.sitemaps.org/schemas/sitemap/0.9}url"):
        lastmod = url.find("{http://www.sitemaps.org/schemas/sitemap/0.9}lastmod")
        lastmod.text = now.strftime("%Y-%m-%dT%H:%M:%S+00:00")

    # Save the updated Sitemap
    updated_file = os.path.join(BACKUP_DIR, f"sitemap_updated_{timestamp}.xml")
    tree = ET.ElementTree(root)
    tree.write(updated_file, encoding='utf-8', xml_declaration=True)

    # Upload the updated Sitemap to the server
    # You can use any method to upload the file to your server

    print("Sitemap updated successfully!")

# Usage example
if __name__ == "__main__":
    update_sitemap()

上述脚本可以通过update_sitemap函数来更新Sitemap,函数会备份当前的Sitemap,并将每个URL的lastmod属性更新为当前日期和时间。然后,更新后的Sitemap将保存在指定的备份目录中,并上传到服务器。

下面是一个使用该脚本的使用例子:

import schedule
import time

# Function to update the Sitemap periodically
def update_sitemap_periodically():
    update_sitemap()

# Schedule the Sitemap update job to run every day at 2 AM
schedule.every().day.at("02:00").do(update_sitemap_periodically)

while True:
    schedule.run_pending()
    time.sleep(1)

在上述例子中,我们使用了schedule库来定期运行update_sitemap_periodically函数,以便每天凌晨2点自动更新Sitemap。您可以根据自己的需求修改定时任务的时间和频率。

需要注意的是,在使用该脚本之前,您需要根据自己的实际情况修改SITEMAP_URLBACKUP_DIR变量,以及相应的上传文件到服务器的代码。

希望这个例子对您有帮助!