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(' ...
随机推荐
- 在ASP.NET Web API中使用OData的Action和Function
本篇体验OData的Action和Function功能.上下文信息参考"ASP.NET Web API基于OData的增删改查,以及处理实体间关系".在本文之前,我存在的疑惑包括: ...
- 将 nginx 安装成 windows 的方法
服务器这几天不稳定,经常性的重启(硬件问题),而且是windows环境,在其上跑了nginx,每次重启后需要手动启动nginx方能是整个系统正常. 所以就查找了下一种方法,能否将nginx做成wind ...
- JPA & Hibernate 注解
1 . @Entity(name="EntityName") 必须 ,name 为可选 , 对应数据库中一的个表 2 . @Table(name="",cata ...
- 关于iosApp审核问题
求各位大神指导!!!!我上周app打包上传给APPstore准备发布,可是苹果官方发来邮件,说我引用了非公有选择,原文如下: Non-public API usage: The app referen ...
- RTP 有效负载(载荷)类型,RTP Payload Type
转自:http://blog.csdn.net/caoshangpa/article/details/53008018 版权声明:本文为灿哥哥http://blog.csdn.net/caoshang ...
- BaseControl按钮合集
BaseControl按钮合集 效果 源码 https://github.com/YouXianMing/Animations // // POPBaseControl.h // Animations ...
- 低版本系统兼容的ActionBar(七)自定义Actionbar标题栏字体
这个自定义字体其实和ActionBar有关,但之前写AtionBar的时候没考虑到修改字体样式,今天看到一篇专门写这个的文章就贴上使用方式.╮(╯▽╰)╭,不得不说Actionbar的那个样式真是让人 ...
- Python 模块 re (Regular Expression)
使用 Python 模块 re 实现解析小工具 概要 在开发过程中发现,Python 模块 re(Regular Expression)是一个很有价值并且非常强大的文本解析工具,因而想要分享一下此 ...
- [转]Apache 配置虚拟主机三种方式
转自: http://www.cnblogs.com/hi-bazinga/archive/2012/04/23/2466605.html 一.基于IP 1. 假设服务器有个IP地址为192.168. ...
- ArrayBlockingQueue, LinkedBlockingQueue, ConcurrentLinkedQueue, RingBuffer
1. ArrayBlockingQueue, LinkedBlockingQueue, ConcurrentLinkedQueue ArrayBlockingQueue, LinkedBlocking ...