利用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/
0
投稿
猜你喜欢
- 前段时间看了一期《最强大脑》,里面各种繁花曲线组合成了非常美丽的图形,一时心血来潮,想尝试自己用代码绘制繁花曲线,想怎么组合就怎么组合。真实
- 目录1. 理解 * 和 ** 2.Python函数的参数 3. 支持任意参数的函数
- 现在有越来越多的个人主页站长需要了解如何如何在windows系统下配置自己的php,cgi服务器,以方便本地调试cgi和php的程序。我们可
- 本文实例为大家了Python中列表(List)的详解操作方法,供大家参考,具体内容如下1.创建列表。只要把逗号分隔的不同的数据项使用方括号括
- 本文实例讲述了Python pymongo模块常用操作。分享给大家供大家参考,具体如下:环境:pymongo3.0.3,python3以下是
- Python转json时出现中文乱码设置报文头# -*- coding:gbk -*- 连接数据库设置编码mysql = MyS
- 什么是fixture在一个测试过程中,fixture主要提供以下功能:为测试提供上下文,比如环境变量,数据集(dataset),提供数据,数
- Xajax是PHP一个不用刷新或者跳到其他页面,就能通过点击组件等与后台后台数据库交互的技术Xajax是php的一个插件,要想使用Xajax
- window.onload=function() {&
- 本文介绍了Sublime开发python程序的示例代码,分享给大家,具体如下:下载、安装Python程序https://www.python
- append(),extend(), insert()都是列表操作中常用的插入函数。其中前两个均接收一个参数,并插入到列表尾部。最后一个接收
- 记录一下PHP连接MySQL的两种方式。先mock一下数据,可以执行一下sql。/*创建数据库*/CREATE DATABASE IF NO
- 进程和线程的区别和联系终于开始加深难度,来到进程和线程的知识点~单就这两个概念,就难倒过不少初学者—&mdash
- 下面是模板的一般形式,显示了指定 SQL 查询和 XPath 查询的方式: <ROOT xmlns:sql="ur
- 在找寻材料的时候,会看到一些暂时用不到但是内容不错的网页,就这样关闭未免浪费掉了,下次也不一定能再次搜索到。有些小伙伴会提出可以保存网页链接
- 饼图概念饼图(pie chart)是用圆形及圆内扇形的角度来表示数值大小的图形,它主要用于表示一个样本(或总体)中各组成部分的数据占全部数据
- 本文实例讲述了Python常见数据结构之栈与队列用法。分享给大家供大家参考,具体如下:Python常见数据结构之-栈首先,栈是一种数据结构。
- 循环是我们经常用到的一个概念,比如,循环计算数字叠加、循环输出文字内容等。循环是运行重复内容的一个最简单的方法,简化了代码流程,增加了时效性
- 举个简单的例子:(此仅限于修改change_form页面)原来的时候,change_form_list是包含这些按钮的:因为此页面继承了{%
- 画矩形函数调用:cv2.rectangle(img,pt1,pt2,color,thickness,line_type,shift)img: