最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

利用Python腳本生成sitemap.xml的實(shí)現(xiàn)方法

 更新時(shí)間:2017年01月31日 09:56:26   作者:PegasusWang  
最近項(xiàng)目中需要用腳本生成sitemap,中間學(xué)習(xí)了一下sitemap的格式和lxml庫(kù)的用法。把結(jié)果記錄一下,方便以后需要直接拿來用。下面這篇文章主要介紹了利用Python腳本生成sitemap.xml的實(shí)現(xiàn)方法,需要的朋友可以參考借鑒,一起來看看吧。

安裝lxml

首先需要pip install lxml安裝lxml庫(kù)。

如果你在ubuntu上遇到了以下錯(cuò)誤:

#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

請(qǐng)安裝以下依賴:

sudo apt-get install libxml2-dev libxslt1-dev

Python代碼

下面是生成sitemap和sitemapindex索引的代碼,可以按照需求傳入需要的參數(shù),或者增加字段:

#!/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)

效果

生成的效果應(yīng)該是這種格式:

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時(shí)間格式的問題

格式是用ISO 8601的標(biāo)準(zhǔn),如果是linux/unix系統(tǒng),可以使用以下函數(shù)獲取

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)

優(yōu)化

一般來說,用lxml效率低并且內(nèi)存占用比較大,可以直接用文件的write方法創(chuàng)建。

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

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用python能帶來一定的幫助,如果有疑問大家可以留言交流。謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • 五個(gè)Pandas?實(shí)戰(zhàn)案例帶你分析操作數(shù)據(jù)

    五個(gè)Pandas?實(shí)戰(zhàn)案例帶你分析操作數(shù)據(jù)

    pandas是基于NumPy的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。Pandas納入了大量庫(kù)和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,提供了高效操作大型數(shù)據(jù)集的工具。pandas提供大量快速便捷地處理數(shù)據(jù)的函數(shù)和方法。你很快就會(huì)發(fā)現(xiàn),它是使Python強(qiáng)大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一
    2022-01-01
  • 詳解如何利用Python制作24點(diǎn)小游戲

    詳解如何利用Python制作24點(diǎn)小游戲

    這篇文章主要為大家詳細(xì)介紹了如何通過Python制作24點(diǎn)小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Python學(xué)習(xí)筆記之lambda表達(dá)式用法詳解

    Python學(xué)習(xí)筆記之lambda表達(dá)式用法詳解

    這篇文章主要介紹了Python學(xué)習(xí)筆記之lambda表達(dá)式用法,結(jié)合實(shí)例形式詳細(xì)分析了lambda表達(dá)式的概念、功能、原理、組成及相關(guān)使用技巧,需要的朋友可以參考下
    2019-08-08
  • Matlab中plot基本用法的具體使用

    Matlab中plot基本用法的具體使用

    這篇文章主要介紹了Matlab中plot基本用法的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • 淺談插入排序算法在Python程序中的實(shí)現(xiàn)及簡(jiǎn)單改進(jìn)

    淺談插入排序算法在Python程序中的實(shí)現(xiàn)及簡(jiǎn)單改進(jìn)

    這篇文章主要介紹了插入排序算法在Python程序中的實(shí)現(xiàn)及簡(jiǎn)單改進(jìn),插入排序算法的最差時(shí)間復(fù)雜度為O(n^2),最優(yōu)時(shí)間復(fù)雜度為O(n),存在一定的優(yōu)化空間,需要的朋友可以參考下
    2016-05-05
  • python 圖像增強(qiáng)算法實(shí)現(xiàn)詳解

    python 圖像增強(qiáng)算法實(shí)現(xiàn)詳解

    這篇文章主要介紹了python 圖像增強(qiáng)算法實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • 一文帶你安裝opencv與常用庫(kù)(保姆級(jí)教程)

    一文帶你安裝opencv與常用庫(kù)(保姆級(jí)教程)

    Python OpenCV是一種流行的計(jì)算機(jī)視覺庫(kù),使用它可以進(jìn)行圖像處理、視頻處理等操作,下面這篇文章主要給大家介紹了關(guān)于安裝opencv與常用庫(kù)的相關(guān)資料,需要的朋友可以參考下
    2023-05-05
  • Flask中endpoint的理解(小結(jié))

    Flask中endpoint的理解(小結(jié))

    這篇文章主要介紹了Flask中endpoint的理解(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 對(duì)django 2.x版本中models.ForeignKey()外鍵說明介紹

    對(duì)django 2.x版本中models.ForeignKey()外鍵說明介紹

    這篇文章主要介紹了對(duì)django 2.x版本中models.ForeignKey()外鍵說明介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • matplotlib之pyplot模塊之標(biāo)題(title()和suptitle())

    matplotlib之pyplot模塊之標(biāo)題(title()和suptitle())

    這篇文章主要介紹了matplotlib之pyplot模塊之標(biāo)題(title()和suptitle()),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02

最新評(píng)論

清丰县| 阳高县| 定兴县| 洛南县| 焦作市| 神池县| 敦化市| 隆回县| 怀远县| 广德县| 临桂县| 缙云县| 福州市| 敦化市| 三江| 类乌齐县| 喜德县| 张掖市| 九寨沟县| 桐乡市| 宁强县| 惠水县| 保靖县| 托克托县| 墨竹工卡县| 永清县| 荔波县| 开原市| 宣汉县| 灌云县| 客服| 色达县| 永嘉县| 应用必备| 内乡县| 南涧| 全椒县| 乌恰县| 通城县| 都安| 固阳县|