项目须要用脚本生成sitemap,中间学习了一下sitemap的格式和lxml库的使用方法。把结果记录一下,方便以后须要直接拿来用。

来自Python脚本生成sitemap


安装lxml

首先须要pip install lxml安装lxml库。

假设你在ubuntu上遇到了下面错误:

#include "libxml/xmlversion.h"

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Removing temporary dir /tmp/pip_build_root...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-O4cIn6-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/lxml
Exception information:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
requirement_set.install(install_options, global_options, root=options.root_path)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1435, in install
requirement.install(install_options, global_options, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 706, in install
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
File "/usr/lib/python2.7/dist-packages/pip/util.py", line 697, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-O4cIn6-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/lxml

请安装下面依赖:

sudo apt-get install libxml2-dev libxslt1-dev


Python代码

下面是生成sitemap和sitemapindex索引的代码。能够依照需求传入须要的參数。或者添加字段:

#!/usr/bin/env python
# -*- coding:utf-8 -*- import io
import re
from lxml import etree def generate_xml(filename, url_list):
"""Generate a new xml file use url_list"""
root = etree.Element('urlset',
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
for each in url_list:
url = etree.Element('url')
loc = etree.Element('loc')
loc.text = each
url.append(loc)
root.append(url) header = u'<? xml version="1.0" encoding="UTF-8"? >\n'
s = etree.tostring(root, encoding='utf-8', pretty_print=True)
with io.open(filename, 'w', encoding='utf-8') as f:
f.write(unicode(header+s)) def update_xml(filename, url_list):
"""Add new url_list to origin xml file."""
f = open(filename, 'r')
lines = [i.strip() for i in f.readlines()]
f.close() old_url_list = []
for each_line in lines:
d = re.findall('<loc>(http:\/\/.+)<\/loc>', each_line)
old_url_list += d
url_list += old_url_list generate_xml(filename, url_list) def generatr_xml_index(filename, sitemap_list, lastmod_list):
"""Generate sitemap index xml file."""
root = etree.Element('sitemapindex',
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
for each_sitemap, each_lastmod in zip(sitemap_list, lastmod_list):
sitemap = etree.Element('sitemap')
loc = etree.Element('loc')
loc.text = each_sitemap
lastmod = etree.Element('lastmod')
lastmod.text = each_lastmod
sitemap.append(loc)
sitemap.append(lastmod)
root.append(sitemap) header = u'<? xml version="1.0" encoding="UTF-8"? >\n'
s = etree.tostring(root, encoding='utf-8', pretty_print=True)
with io.open(filename, 'w', encoding='utf-8') as f:
f.write(unicode(header+s)) if __name__ == '__main__':
urls = ['http://www.baidu.com'] * 10
mods = ['2004-10-01T18:23:17+00:00'] * 10
generatr_xml_index('index.xml', urls, mods)

效果

生成的效果应该是这样的格式:

sitemap格式:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/foo.html</loc>
</url>
</urlset>

sitemapindex格式:

<?

xml version="1.0" encoding="UTF-8"?

>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://www.example.com/sitemap1.xml.gz</loc>
<lastmod>2004-10-01T18:23:17+00:00</lastmod>
</sitemap>
<sitemap>
<loc>http://www.example.com/sitemap2.xml.gz</loc>
<lastmod>2005-01-01</lastmod>
</sitemap>
</sitemapindex>

lastmod时间格式的问题

格式是用ISO 8601的标准,假设是linux/unix系统,能够使用下面函数获取

def get_lastmod_time(filename):
time_stamp = os.path.getmtime(filename)
t = time.localtime(time_stamp)
return time.strftime('%Y-%m-%dT%H:%M:%S+08:00', t)

Ref:

创建站点地图

sitemap

lxml

谷歌(Google)站点地图的XML文档格式说明

Google Sitemap文件格式

Python脚本生成sitemap的更多相关文章

  1. 利用Python 脚本生成 .h5 文件 代码

    利用Python 脚本生成 .h5 文件 import os, json, argparse from threading import Thread from Queue import Queue ...

  2. python 使用py2exe将python 脚本生成exe可执行文件

    使用python的py2exe模块可以很容易地帮助我们将python脚本生成可执行的exe程序.这样我们就可以让脚本脱离虚拟机的束缚,从而独立运行. 首先安装py2exe分解步骤如下:(pip和eas ...

  3. Python脚本生成可执行文件&(恋爱小脚本)

    Python脚本生成可执行文件&(恋爱小脚本) 参考文献: http://c.biancheng.net/view/2690.html; https://blog.csdn.net/qq_39 ...

  4. 用 Python脚本生成 Android SALT 扰码

    发布Android 有偿应用时需要随机生成 SALT 扰码夹在文件中,以下是 Python脚本(当然你选择 C/Java/SHELL/Perl 或别的都行) #!/usr/bin/python # F ...

  5. python脚本生成exe程序

    去年十一月换了新公司后,一直没闲着,马不停蹄地接不同的需求,一个版本一个版本的迭代,也没时间研究python了.十一休假归来,某日,老婆问金融量化需要学python吗?并分享了一个公众号文章,内容是吹 ...

  6. python脚本生成exe可执行文件

    1.先安装第三方插件: py2exe. Get py2exe from http://www.py2exe.org/ 在download里下载与自己python对应的版本 2.写一个测试python文 ...

  7. pyinstaller将python脚本生成exe

    一.下载pyinstaller 二.生成exe 下载pyinstaller 1.在C:\python27\Scripts目录下打开cmd界面,执行命令:pip install PyInstaller ...

  8. python小白记录一 ——python脚本生成windows可执行exe

    1.需要安装pywin32 先查看自己有没有安装:使用如下命令查看 pip show pywin32 如果没有则用下面方式进行安装: pip install pywin32 然后等待安装完成: 2.再 ...

  9. Python 脚本生成测试数据,Python生成随机数据,Python生成大量数据保存到文件夹中

    代码如下: import random import datetime import time dataCount = 10*100*100 #10M. codeRange = range(ord(' ...

随机推荐

  1. ProFTPd Local pr_ctrls_connect Vulnerability - ftpdctl 漏洞及攻击代码分析

    攻击代码网址:http://www.exploit-db.com/exploits/394/ 1.执行环境: 1.ProFTPD 1.3.0/1.3.0a 2.编译ProFTPD时.--enable- ...

  2. Windows Phone本地数据库(SQLCE):3、[table]attribute(翻译) (转)

    这是“windows phone mango本地数据库(sqlce)”系列短片文章的第三篇. 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知 ...

  3. PPT幻灯片放映不显示备注,只让备注显示在自己屏幕上-投影机 设置

    无论是老师或是讲师还是即将要演讲的人,在讲课之前一定会做好课件,到哪一页该讲哪些内容,到哪里该如何去讲等等.那么一般的讲师会将这些课件存放到哪里呢?是用个书本记载下来呢,还是直接存放到电脑上呢?其实本 ...

  4. ormlite 在android中 排序 条件查询

    ormlite 在android中 排序 条件查询 all = dao.queryBuilder().orderBy("Id", true).where().eq("Ty ...

  5. 初学者必读:IBM长文解读人工智能、机器学习和认知计算

    转自:https://zhuanlan.zhihu.com/p/27228015?utm_source=weibo&utm_medium=social 人工智能的发展曾经经历过几次起起伏伏,近 ...

  6. Material Designer的低版本兼容实现(二)—— Theme

    Theme material主题可以定义为如下形式: @android:style/Theme.Material @android:style/Theme.Material.Light @androi ...

  7. JAVA垃圾回收机制概要

    垃圾回收是JAVA中的一个大知识点,也是一个著名知识点,毕竟JAVA号称自己先进性的时候总是会带上垃圾回收.于是,它也成了面试中的常客,面试官动不动的就要你解释下什么是垃圾回收,以及它的原理是什么.当 ...

  8. Android系统版本与API等级对应关系表

    从Android官网拷过来的,方便查阅... 官网地址:https://developer.android.com/guide/topics/manifest/uses-sdk-element.htm ...

  9. ubuntu修改软链接

    https://blog.csdn.net/u012897374/article/details/79199336 添加软连接(symbol link)相当于添加一个快捷方式,解决cannot ope ...

  10. [转]thinkphp在iis下的rewrite伪静态的配置方法

    From : http://code-tech.diandian.com/post/2012-11-12/40042151797 首先你要安装IIS下的rewrite组建,下载地址:Rewrite.z ...