利用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 相关文章推荐
python paramiko实现ssh远程访问的方法
Dec 03 Python
详解Python命令行解析工具Argparse
Apr 20 Python
Python 将RGB图像转换为Pytho灰度图像的实例
Nov 14 Python
使用python为mysql实现restful接口
Jan 05 Python
Jupyter中直接显示Matplotlib的图形方法
May 24 Python
基于python绘制科赫雪花
Jun 22 Python
Python3匿名函数lambda介绍与使用示例
May 18 Python
python2和python3应该学哪个(python3.6与python3.7的选择)
Oct 01 Python
Pytorch转onnx、torchscript方式
May 25 Python
Python过滤掉numpy.array中非nan数据实例
Jun 08 Python
Django限制API访问频率常用方法解析
Oct 12 Python
python 闭包函数详细介绍
Apr 19 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编程开发“虚拟域名”系统
2006/10/09 PHP
Windows下安装Memcached的步骤说明
2010/04/25 PHP
初学Jquery插件制作 在SageCRM的查询屏幕隐藏部分行的功能
2011/12/26 Javascript
多个checkbox被选中时如何判断是否有自己想要的
2014/09/22 Javascript
windows8.1+iis8.5下安装node.js开发环境
2014/12/12 Javascript
分享2个jQuery插件--jquery.fileupload与artdialog
2014/12/26 Javascript
简介JavaScript中setUTCSeconds()方法的使用
2015/06/12 Javascript
ReactNative-JS 调用原生方法实例代码
2016/10/08 Javascript
jQuery实现立体式数字滚动条增加效果
2016/12/21 Javascript
MUI 解决动态列表页图片懒加载再次加载不成功的bug问题
2017/04/13 Javascript
NodeJS使用七牛云存储上传文件的方法
2017/07/24 NodeJs
浅谈vue项目如何打包扔向服务器
2018/05/08 Javascript
vue实现抖音时间转盘
2019/09/08 Javascript
JavaScript setTimeout()基本用法有哪些
2020/11/04 Javascript
vant 中van-list的用法说明
2020/11/11 Javascript
轻松实现python搭建微信公众平台
2016/02/16 Python
详解Python中的array数组模块相关使用
2016/07/05 Python
基于Python实现对PDF文件的OCR识别
2016/08/05 Python
解决phantomjs截图失败,phantom.exit位置的问题
2018/05/17 Python
Python基于pyCUDA实现GPU加速并行计算功能入门教程
2018/06/19 Python
详解python单元测试框架unittest
2018/07/02 Python
对TensorFlow的assign赋值用法详解
2018/07/30 Python
python 将列表中的字符串连接成一个长路径的方法
2018/10/23 Python
Python分支语句与循环语句应用实例分析
2019/05/07 Python
Python 正则表达式 re.match/re.search/re.sub的使用解析
2019/07/22 Python
python实现爬虫抓取小说功能示例【抓取金庸小说】
2019/08/09 Python
PyCharm 2020.2 安装详细教程
2020/09/25 Python
6号汽车旅馆预订:Motel 6
2018/02/11 全球购物
美国在线家居装饰店:Belle&June
2018/10/24 全球购物
中秋节国旗下演讲稿
2014/09/05 职场文书
党员批评与自我批评发言
2014/10/02 职场文书
夫妻双方自愿离婚协议书怎么写
2014/12/01 职场文书
2015银行年终工作总结范文
2015/05/26 职场文书
酒店温馨提示语
2015/07/14 职场文书
2019年特色火锅店的创业计划书模板
2019/08/28 职场文书
用CSS3画一个爱心
2021/04/27 HTML / CSS