美文网首页
利用Python生成sitemap脚本

利用Python生成sitemap脚本

作者: 微凉_半夏 | 来源:发表于2019-01-29 17:18 被阅读0次

在网站seo中,有时候需要我们提交网站地图到搜索引擎中,用以提高搜索排名等
由于平时用Google比较多,所以我将以谷歌搜索引擎为例
注:根据Google官方提供的说明,每一个sitemap的xml文件中最大只支持5w个url,大小不超过50M,可根据需求进行修改
下面,我将python语言自动生成sitemap的xml文件

# -*- coding:utf-8 -*-

import datetime
import re


# def get_url():
#     with open('D:\\Excel\\sitemap\\可用.txt', 'r', encoding='UTF-8') as f:
#         list1 = []
#         for i in f:
#             line = i.strip()
#             list1.append(line)

#         return list1


def creat_xml(filename, url_list):  # 生成sitemap所需要的xml方法
    header = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    file = open(filename, 'a', encoding='utf-8')
    file.writelines(header)
    file.close()

    for url in url_list:
        times = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
        urls = re.sub(r"&", "&amp;", url)  # 注意这里,在URL中如果含有&将会出错,所以需要进行转义

        # 这个是生成的主体,可根据需求进行修改
        ment = "  <url>\n    <loc>%s</loc>\n    <lastmod>%s</lastmod>\n    <changefreq>weekly</changefreq>\n    <priority>0.8</priority>\n  </url>\n" % (urls, times)

        file = open(filename, 'a', encoding='utf-8')
        file.writelines(ment)
        file.close()

    last = "</urlset>"
    file = open(filename, 'a', encoding='utf-8')
    file.writelines(last)
    file.close()


if __name__ == '__main__':
    # url_list = get_url()
    url_list = ['https://search.google.com', 'https://www.google.com', 'https://translate.google.cn']
    creat_xml("D:\\Excel\\sitemap\\test1.xml", url_list)

以下是生成后的结果:


test.png

相关文章

网友评论

      本文标题:利用Python生成sitemap脚本

      本文链接:https://www.haomeiwen.com/subject/iqnxsqtx.html