利用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中循环语句的嵌套使用
May 14 Python
深入理解Python中字典的键的使用
Aug 19 Python
python制作websocket服务器实例分享
Nov 20 Python
Python实现随机生成手机号及正则验证手机号的方法
Apr 25 Python
django 发送邮件和缓存的实现代码
Jul 18 Python
Python求一批字符串的最长公共前缀算法示例
Mar 02 Python
Python交互式图形编程的实现
Jul 25 Python
如何基于Python + requests实现发送HTTP请求
Jan 13 Python
python入门之井字棋小游戏
Mar 05 Python
jupyter note 实现将数据保存为word
Apr 14 Python
升级keras解决load_weights()中的未定义skip_mismatch关键字问题
Jun 12 Python
Numpy中np.random.rand()和np.random.randn() 用法和区别详解
Oct 23 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(2)――PHP类型
2010/02/15 PHP
PHP对XML内容进行修改和删除实例代码
2016/10/26 PHP
PHP 图片处理
2020/09/16 PHP
JS实现多物体缓冲运动实例代码
2013/11/29 Javascript
document节点对象的获取方式示例介绍
2013/12/24 Javascript
JavaScript日期时间格式化函数分享
2014/05/05 Javascript
JS实现从网页顶部掉下弹出层效果的方法
2015/08/06 Javascript
浅谈DOCTYPE对$(window).height()取值的影响
2016/07/21 Javascript
D3.js实现雷达图的方法详解
2016/09/22 Javascript
JavaScript实现倒计时跳转页面功能【实用】
2016/12/13 Javascript
setTimeout学习小结
2017/02/08 Javascript
JS验证input输入框(字母,数字,符号,中文)
2017/03/23 Javascript
基于vue-cli创建的项目的目录结构及说明介绍
2017/11/23 Javascript
详解webpack的proxyTable无效的解决方案
2018/06/15 Javascript
详解javascript中的babel到底是什么
2018/06/21 Javascript
微信小程序module.exports模块化操作实例浅析
2018/12/20 Javascript
Vue数据驱动表单渲染,轻松搞定form表单
2019/07/19 Javascript
解决echarts中横坐标值显示不全(自动隐藏)问题
2020/07/20 Javascript
[04:26]DOTA2上海特锦赛小组赛第二日 TOP10精彩集锦
2016/02/27 DOTA
web.py中调用文件夹内模板的方法
2014/08/26 Python
jupyter notebook中美观显示矩阵实例
2020/04/17 Python
解决Jupyter notebook中.py与.ipynb文件的import问题
2020/04/21 Python
通用的Django注册功能模块实现方法
2021/02/05 Python
CSS3实现王者荣耀匹配人员加载页面的方法
2019/04/16 HTML / CSS
CSS3 分类菜单效果
2019/05/27 HTML / CSS
工地门卫岗位职责
2013/12/30 职场文书
小学生暑假感言
2014/02/06 职场文书
创建文明学校实施方案
2014/03/11 职场文书
春节联欢会主持词
2014/03/24 职场文书
学生个人自我鉴定范文
2014/03/28 职场文书
股东协议书
2014/04/14 职场文书
环境建议书
2015/02/04 职场文书
公司酒会致辞
2015/07/30 职场文书
MySQL中你可能忽略的COLLATION实例详解
2021/05/12 MySQL
Netty结合Protobuf进行编解码的方法
2021/06/26 Java/Android
Python实现抖音热搜定时爬取功能
2022/03/16 Python