Python脚本生成sitemap
项目须要用脚本生成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的更多相关文章
- 利用Python 脚本生成 .h5 文件 代码
利用Python 脚本生成 .h5 文件 import os, json, argparse from threading import Thread from Queue import Queue ...
- python 使用py2exe将python 脚本生成exe可执行文件
使用python的py2exe模块可以很容易地帮助我们将python脚本生成可执行的exe程序.这样我们就可以让脚本脱离虚拟机的束缚,从而独立运行. 首先安装py2exe分解步骤如下:(pip和eas ...
- Python脚本生成可执行文件&(恋爱小脚本)
Python脚本生成可执行文件&(恋爱小脚本) 参考文献: http://c.biancheng.net/view/2690.html; https://blog.csdn.net/qq_39 ...
- 用 Python脚本生成 Android SALT 扰码
发布Android 有偿应用时需要随机生成 SALT 扰码夹在文件中,以下是 Python脚本(当然你选择 C/Java/SHELL/Perl 或别的都行) #!/usr/bin/python # F ...
- python脚本生成exe程序
去年十一月换了新公司后,一直没闲着,马不停蹄地接不同的需求,一个版本一个版本的迭代,也没时间研究python了.十一休假归来,某日,老婆问金融量化需要学python吗?并分享了一个公众号文章,内容是吹 ...
- python脚本生成exe可执行文件
1.先安装第三方插件: py2exe. Get py2exe from http://www.py2exe.org/ 在download里下载与自己python对应的版本 2.写一个测试python文 ...
- pyinstaller将python脚本生成exe
一.下载pyinstaller 二.生成exe 下载pyinstaller 1.在C:\python27\Scripts目录下打开cmd界面,执行命令:pip install PyInstaller ...
- python小白记录一 ——python脚本生成windows可执行exe
1.需要安装pywin32 先查看自己有没有安装:使用如下命令查看 pip show pywin32 如果没有则用下面方式进行安装: pip install pywin32 然后等待安装完成: 2.再 ...
- Python 脚本生成测试数据,Python生成随机数据,Python生成大量数据保存到文件夹中
代码如下: import random import datetime import time dataCount = 10*100*100 #10M. codeRange = range(ord(' ...
随机推荐
- CLR是如何被加载并工作的
当运行Windows应用程序的时候,CLR总是默默地为服务着.CLR到底是如何被加载并运行呢? 首先,Microsoft专门为CLR定义了一个标准的COM接口. 安装某个版本的.NET Framewo ...
- SQLCE使用
Windows Phone的本地数据库SQL Server CE是7.1版本即芒果更新的新特性,所以你要在应用程序中使用SQL Server CE数据库必须使用Windows Phone 7.1的AP ...
- Android开发中,比较有特色的特性(与iOS相比)
1.界面代码和界面控件元素时时联动.同步 2.当我们创建一个Activity时,系统自动帮我们维护strings.xml 文件和AndroidManifest.xml文件. 3.有来无回,删除.修改时 ...
- ios(包括6、7)应用程序引用系统通讯录的方法 [亲测可行]
由于ios系统对用户隐私的控制,第三方应用程序只能通过苹果官方接口调用系统通讯录,不能像android那样直接操作通讯录数据库. 一般地,使用系统自带通讯录的方法有两种,一种是直接将整个通讯录 ...
- [LNU.Machine Learning.Question.1]梯度下降方法的一些理解
曾经学习machine learning,在regression这一节,对求解最优化问题的梯度下降方法,理解总是处于字面意义上的生吞活剥. 对梯度的概念感觉费解?到底是标量还是矢量?为什么沿着负梯度方 ...
- SQLUnit 环境搭建
1 技术须要积累 前几天去一位笛友小赖家玩,才知道他的笛子吹得好不是偶然.是由于他真的用功了,电脑里面下载有超多的视频.教程等!这真的非常让我震撼!一直是在公司做技术,但资料考不出来,而我整理了多少技 ...
- LeakCanary 原理浅析
前言 提到Java语言的特点,无论是教科书还是程序员一般都会罗列出面向对象.可移植性及安全等特点.但如果你是一位刚从C/C++转到Java的程序员,对Java语言的特性除了面向对象之外,最外直接的应当 ...
- List转换为字符串并添加分隔符
// 方法一: public String listToString(List list, char separator) { StringBuilder sb = new StringBuilder ...
- Orchard之在前台显式一个属于自己的列表
一:当前现状 Orchard 并不提供筛选 Owner 的 Query,但是 Gallery 中有提供,那就是:Owner Queries. Install 之,然后在解决方案中引入该 Project ...
- Orchard之创建列表
一:首先需要确保 List Module 的开始 即: Enable 之后,左边的列表中,多了一个 List 功能菜单. 二:为 Content type 选定 Cotainable 不再赘述. 三: ...