项目须要用脚本生成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. .NET轻量级DBHelpers数据访问组件

    一.摘要 一说到ADO.NET大家可能立刻想到的就是增.删.改.查(CRUD)操作,然后再接就想到项目中的SQLHelper.没错本课分享课阿笨给大家带来的是来源于github上开源的DAO数据库访问 ...

  2. Android: INSTALL_FAILED_UPDATE_INCOMPATIBLE错误解决措施

    晚上在测一个widget,前面测的好好的,后面再安装的时候发现如下错误:[2009-06-07 02:39:35 - battery] Performing sync[2009-06-07 02:39 ...

  3. ASP.NET MVC异步验证是如何工作的03,jquery.validate.unobtrusive.js是如何工作的

    在上一篇"ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建"中了解了ASP.NET异步验证是如何创建表单元素的,本篇体验jquery.validate.uno ...

  4. window.onbeforeunload() 事件调用ajax

    经常有这样的需求,就是在离开某个web页面时,用户不一定点注销,这样会导致会话不能及时销毁.为实现用户离开页面时,自动注销功能,需要在web页面的onbeforeunload事件处理函数中发送注销命令 ...

  5. C#编程(十八)----------C#中的结构

    C#中的结构 假设有一个类: class Dimensions { public double Length; public double Width; } 定义了一个类,它只存储某一项的长度和宽度. ...

  6. java List转换为字符串并加入分隔符的一些方法总结

    方法一: public String listToString(List list, char separator) { StringBuilder sb = new StringBuilder(); ...

  7. java如何直接返回excel到客户端

    既然是web项目首先你得拿到响应才能向外部写出,你得拿到响应对象response,1.添加如下两行代码response.setContentType("application/vnd..ms ...

  8. 详细解读LruCache类

    LruCache是android提供的一个缓存工具类,其算法是最近最少使用算法.它把最近使用的对象用“强引用”存储在LinkedHashMap中,并且把最近最少使用的对象在缓存值达到预设定值之前就从内 ...

  9. C# Linq获取两个List或数组的差集交集

      List<); list1.Add(); list1.Add(); List<); list2.Add(); list2.Add(); //得到的结果是4,5 即减去了相同的元素. L ...

  10. 可重入读写锁ReentrantReadWriteLock基本原理分析

    前言 本篇适用于了解ReentrantLock或ReentrantReadWriteLock的使用,但想要进一步了解原理的读者.见于之前的分析都是借鉴大量的JDK源码,这次以流程图的形式代替源码,希望 ...