利用Python脚本生成sitemap.xml的实现方法
作者:PegasusWang 发布时间:2021-03-16 22:32:32
标签:python,脚本,sitemap.xml
安装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)
return time.strftime('%Y-%m-%dT%H:%M:%SZ', t)
优化
一般来说,用lxml效率低并且内存占用比较大,可以直接用文件的write方法创建。
def generate_xml(filename, url_list):
with gzip.open(filename,"w") as f:
f.write("""<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n""")
for i in url_list:
f.write("""<url><loc>%s</loc></url>\n"""%i)
f.write("""</urlset>""")
def append_xml(filename, url_list):
with gzip.open(filename, 'r') as f:
for each_line in f:
d = re.findall('<loc>(http:\/\/.+)<\/loc>', each_line)
url_list.extend(d)
generate_xml(filename, set(url_list))
def modify_time(filename):
time_stamp = os.path.getmtime(filename)
t = time.localtime(time_stamp)
return time.strftime('%Y-%m-%dT%H:%M:%S:%SZ', t)
def new_xml(filename, url_list):
generate_xml(filename, url_list)
root = dirname(filename)
with open(join(dirname(root), "sitemap.xml"),"w") as f:
f.write('<?xml version="1.0" encoding="utf-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
for i in glob.glob(join(root,"*.xml.gz")):
lastmod = modify_time(i)
i = i[len(CONFIG.SITEMAP_PATH):]
f.write("<sitemap>\n<loc>http:/%s</loc>\n"%i)
f.write("<lastmod>%s</lastmod>\n</sitemap>\n"%lastmod)
f.write('</sitemapindex>')
来源:http://ningning.today/2015/07/23/web/用Python脚本生成sitemap-xml/


猜你喜欢
- 一、Request对象Request对象主要是用来请求数据,爬取一页的数据重新发送一个请求的时候调用,其源码类的位置如下图所示:这里给出其的
- 这篇文章主要介绍了Python类如何定义私有变量,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以
- 本文实例讲述了Python网络编程之TCP与UDP协议套接字用法。分享给大家供大家参考,具体如下:TCP协议服务器端:#!/usr/bin/
- MySQL数据库具有跨平台性,不仅可以在Windows上运行,还可以在UNIX,Linux和Mac OS等操作系统上运行 1.先简
- 前言:线程安全问题:当2个线程同时用到线程池时,会同时创建2个线程池。如果多个线程,错开用到线程池,就只会创建一个线程池,会共用一个线程池。
- 解决SQL2000最大流水号的两个好方法问:请问怎样才能解决ms serer 2000 最大流水号的问题?答:我可以介绍两种方法给你:方法1
- 在日常工作或生活中,总避免不了需要操作文件或文件夹,比如希望找出电脑中所有临时文件并清除,或者找到指定文件夹内所有图片文件并进行重新命名等等
- 一,索引的重要性索引用于快速找出在某个列中有一特定值的行。不使用索引,MySQL必须从第1条记录开始然后读完整个表直到找出相关的行。表越大,
- 统计分析常常会出错、存在偏见或过于狭隘。数字崇拜者常因专注于统计分析而把可用性研究引入歧途。强调洞察力和定性研究更为重要。用户研究有两种类型
- 1、net/http爬虫net/http配合正则表达式爬虫。package mainimport ("fmt""
- 需求:给定一个数组和一个正整数,要求把数组分割成多个正整数大小的数组,如果不够分,则最后一个数组分到剩余的所有元素。示例1:数组:[1, 2
- 索引是提高数据查询最有效的方法,也是最难全面掌握的技术,因为正确的索引可能使效率提高10000倍,而无效的索引可能是浪费了数据库空间,甚至大
- 本文实例讲述了Python使用pylab库实现绘制直方图功能。分享给大家供大家参考,具体如下:Python直方图#!/usr/bin/pyt
- 注:本文所指的YUV均为YUV420中的I420格式(最常见的一种),其他格式不能用以下的代码。位深为8bit时,每个像素占用1字节,对应文
- 哎,以前写博文的时候没注意,有些图片用QQ来截取,获得的图片文件名都是类似于QQ截图20120926174732-300×15.png的形式
- python的PIL库简直好用的不得了,PIL下面的Image库更是封装了很多对图片处理的函数,关于Image库的介绍和使用,看这里:htt
- 构建运动模糊模型现假定相机不动,图像f(x,y)在图像面上移动并且图像f(x,y)除移动外不随时间变化。令x0(t)和y0(t)分别代表位移
- 这篇文章主要介绍了python如何获取apk的packagename和activity,文中通过示例代码介绍的非常详细,对大家的学习或者工作
- 不知不觉的玩了两年多的MySQL,发现很多人都说MySQL对比Oracle来说,优化器做的比较差,其实某种程度上来说确实是这样,
- 大部分面向对象的编程语言(除了C++)都只支持单继承,而不支持多继承,为什么呢?因为多继承不仅增加编程复杂度,而且容易导致莫名其妙的错误。P