利用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实现判断数组是否包含指定元素的方法
Jul 15 Python
python套接字流重定向实例汇总
Mar 03 Python
python提取图像的名字*.jpg到txt文本的方法
May 10 Python
Python实现的本地文件搜索功能示例【测试可用】
May 30 Python
Pandas GroupBy对象 索引与迭代方法
Nov 16 Python
python实现海螺图片的方法示例
May 12 Python
使用Python画股票的K线图的方法步骤
Jun 28 Python
Django1.11配合uni-app发起微信支付的实现
Oct 12 Python
wxpython绘制圆角窗体
Nov 18 Python
Python+Selenium+phantomjs实现网页模拟登录和截图功能(windows环境)
Dec 11 Python
对tensorflow 中tile函数的使用详解
Feb 07 Python
python图片验证码识别最新模块muggle_ocr的示例代码
Jul 03 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
php上传、管理照片示例
2006/10/09 PHP
浅析Mysql 数据回滚错误的解决方法
2013/08/05 PHP
php生成xml时添加CDATA标签的方法
2014/10/17 PHP
PHP变量赋值、代入给JavaScript中的变量
2015/06/29 PHP
PHP CURL采集百度搜寻结果图片不显示问题的解决方法
2017/02/03 PHP
PHP面向对象五大原则之依赖倒置原则(DIP)详解
2018/04/08 PHP
form中限制文本字节数js代码
2007/06/10 Javascript
js同时按下两个方向键
2007/12/01 Javascript
解析John Resig Simple JavaScript Inheritance代码
2012/12/03 Javascript
一款基于jQuery的图片场景标注提示弹窗特效
2015/01/05 Javascript
纯javascript响应式树形菜单效果
2015/11/10 Javascript
jQuery隐藏和显示效果实现
2016/04/06 Javascript
DWR中各种java方法的调用
2016/05/04 Javascript
jQuery选择器基础入门教程
2016/05/10 Javascript
设置点击文本框或图片弹出日历控件的实现代码
2016/05/12 Javascript
bootstrap modal+gridview实现弹出框效果
2017/08/15 Javascript
vue页面离开后执行函数的实例
2018/03/13 Javascript
angularJs中ng-model-options设置数据同步的方法
2018/09/30 Javascript
angular ng-model 无法获取值的处理方法
2018/10/02 Javascript
vue-cli3.0 脚手架搭建项目的过程详解
2018/10/19 Javascript
vue实现图书管理系统
2020/12/29 Vue.js
python基础入门学习笔记(Python环境搭建)
2016/01/13 Python
Flask框架Flask-Login用法分析
2018/07/23 Python
python3对拉勾数据进行可视化分析的方法详解
2019/04/03 Python
python实现对图片进行旋转,放缩,裁剪的功能
2019/08/07 Python
Python使用Turtle模块绘制国旗的方法示例
2021/02/28 Python
利用CSS3制作简单的3d半透明立方体图片展示
2017/03/25 HTML / CSS
html5使用canvas压缩图片的示例代码
2018/09/11 HTML / CSS
美国面料纺织品商城:Fabric.com
2017/06/28 全球购物
Stutterheim瑞典:瑞典高级外套时装品牌
2019/06/24 全球购物
优秀经理事迹材料
2014/02/01 职场文书
2014小学植树节活动总结
2014/03/10 职场文书
2014年四风问题个人对照自查剖析材料
2014/09/15 职场文书
名人传读书笔记
2015/06/26 职场文书
2016年“节能宣传周”活动总结
2016/04/05 职场文书