利用Python脚本生成sitemap.xml的实现方法


Posted in Python onJanuary 31, 2017

安装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>')

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流。谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python3读取UTF-8文件及统计文件行数的方法
May 22 Python
Python实现telnet服务器的方法
Jul 10 Python
【Python】Python的urllib模块、urllib2模块批量进行网页下载文件
Nov 19 Python
Python 互换字典的键值对实例
Feb 12 Python
解决Django加载静态资源失败的问题
Jul 28 Python
django商品分类及商品数据建模实例详解
Jan 03 Python
Django框架获取form表单数据方式总结
Apr 22 Python
python解释器安装教程的方法步骤
Jul 02 Python
python程序如何进行保存
Jul 03 Python
带你学习Python如何实现回归树模型
Jul 16 Python
从零开始的TensorFlow+VScode开发环境搭建的步骤(图文)
Aug 31 Python
python 解决Windows平台上路径有空格的问题
Nov 10 Python
利用python实现命令行有道词典的方法示例
Jan 31 #Python
Python爬虫包 BeautifulSoup  递归抓取实例详解
Jan 28 #Python
python 编程之twisted详解及简单实例
Jan 28 #Python
详解python之简单主机批量管理工具
Jan 27 #Python
Python下的Softmax回归函数的实现方法(推荐)
Jan 26 #Python
在Django同1个页面中的多表单处理详解
Jan 25 #Python
Python heapq使用详解及实例代码
Jan 25 #Python
You might like
php下判断数组中是否存在相同的值array_unique
2008/03/25 PHP
php中的常用魔术方法汇总
2016/02/14 PHP
php fseek函数读取大文件两种方法
2016/10/12 PHP
PHP抽象类基本用法示例
2018/12/28 PHP
js 函数的执行环境和作用域链的深入解析
2009/11/01 Javascript
jquery 简单图片导航插件jquery.imgNav.js
2010/03/17 Javascript
JavaScript实现页面实时显示当前时间的简单实例
2013/07/20 Javascript
浅析jQuery(function(){})与(function(){})(jQuery)之间的区别
2014/01/09 Javascript
js数组循环遍历数组内所有元素的方法
2014/01/18 Javascript
jQuery查找节点并获取节点属性的方法
2016/09/09 Javascript
浅谈js中用$(#ID)来作为选择器的问题(id重复的时候)
2017/02/14 Javascript
Vue中保存用户登录状态实例代码
2017/06/07 Javascript
Vue.js对象转换实例
2017/06/07 Javascript
提高Node.js性能的应用技巧分享
2017/08/10 Javascript
Vue基于NUXT的SSR详解
2017/10/24 Javascript
深入了解JavaScript 私有化
2019/05/30 Javascript
解决layui-table单元格设置为百分比在ie8下不能自适应的问题
2019/09/28 Javascript
node.js文件操作系统实例详解
2019/11/05 Javascript
vue使用swiper实现中间大两边小的轮播图效果
2019/11/24 Javascript
JavaScript Date对象功能与用法学习记录
2020/04/28 Javascript
基于ant design日期控件使用_仅月份的操作
2020/10/27 Javascript
python类继承用法实例分析
2015/05/27 Python
Python基于sftp及rsa密匙实现远程拷贝文件的方法
2016/09/21 Python
python微信公众号之关注公众号自动回复
2018/10/25 Python
Python安装selenium包详细过程
2019/07/23 Python
Python流程控制 if else实现解析
2019/09/02 Python
python基于gevent实现并发下载器代码实例
2019/11/01 Python
Static Nested Class 和 Inner Class的不同
2013/11/28 面试题
应聘教师自荐信
2013/10/12 职场文书
监理资料员岗位职责
2014/01/03 职场文书
社区党建工作汇报材料
2014/08/14 职场文书
工作粗心大意检讨书
2014/09/18 职场文书
大学班干部竞选稿
2015/11/20 职场文书
python 实现德洛内三角剖分的操作
2021/04/22 Python
Oracle配置dblink访问PostgreSQL的操作方法
2022/03/21 PostgreSQL
canvas 中如何实现物体的框选
2022/08/05 Javascript