> Java > java지도 시간 > 본문

Python 스크립트를 사용하여 sitemap.xml을 생성하는 방법

高洛峰
풀어 주다: 2017-02-04 11:51:41
원래의
1502명이 탐색했습니다.

lxml 설치

먼저 lxml 라이브러리를 설치하려면 pip install 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 코드

다음은 사이트맵 및 사이트맵 인덱스 색인을 생성하는 코드입니다. 필요에 따라 필수 매개변수를 전달하거나 필드를 추가할 수 있습니다.

#!/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&#39;<?xml version="1.0" encoding="UTF-8"?>\n&#39;
  s = etree.tostring(root, encoding=&#39;utf-8&#39;, pretty_print=True)
  with io.open(filename, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:
    f.write(unicode(header+s))
 
 
def update_xml(filename, url_list):
  """Add new url_list to origin xml file."""
  f = open(filename, &#39;r&#39;)
  lines = [i.strip() for i in f.readlines()]
  f.close()
 
  old_url_list = []
  for each_line in lines:
    d = re.findall(&#39;<loc>(http:\/\/.+)<\/loc>&#39;, 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(&#39;sitemapindex&#39;,
             xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
  for each_sitemap, each_lastmod in zip(sitemap_list, lastmod_list):
    sitemap = etree.Element(&#39;sitemap&#39;)
    loc = etree.Element(&#39;loc&#39;)
    loc.text = each_sitemap
    lastmod = etree.Element(&#39;lastmod&#39;)
    lastmod.text = each_lastmod
    sitemap.append(loc)
    sitemap.append(lastmod)
    root.append(sitemap)
 
  header = u&#39;<?xml version="1.0" encoding="UTF-8"?>\n&#39;
  s = etree.tostring(root, encoding=&#39;utf-8&#39;, pretty_print=True)
  with io.open(filename, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:
    f.write(unicode(header+s))
 
 
if __name__ == &#39;__main__&#39;:
  urls = [&#39;http://www.baidu.com&#39;] * 10
  mods = [&#39;2004-10-01T18:23:17+00:00&#39;] * 10
  generatr_xml_index(&#39;index.xml&#39;, urls, mods)
로그인 후 복사

Effect

생성된 효과는 다음과 같아야 합니다.

사이트맵 형식:

<?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>
로그인 후 복사

사이트맵 인덱스 형식:

<?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(&#39;%Y-%m-%dT%H:%M:%S+08:00&#39;, t)
  return time.strftime(&#39;%Y-%m-%dT%H:%M:%SZ&#39;, t)
로그인 후 복사

🎜>일반적으로 lxml을 사용하는 것은 비효율적이며 시간을 많이 차지합니다. 많은 메모리를 파일의 쓰기 방법을 사용하여 직접 만들 수 있습니다.

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, &#39;r&#39;) as f:
    for each_line in f:
      d = re.findall(&#39;<loc>(http:\/\/.+)<\/loc>&#39;, 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(&#39;%Y-%m-%dT%H:%M:%S:%SZ&#39;, 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(&#39;<?xml version="1.0" encoding="utf-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n&#39;)
    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(&#39;</sitemapindex>&#39;)
로그인 후 복사


요약

위 내용은 이 기사의 전체 내용입니다. 이 기사의 내용이 학습하는 모든 사람에게 도움이 되기를 바랍니다. 또는 Python을 사용하여 도움을 받으려면 질문이 있는 경우 메시지를 남겨서 소통할 수 있습니다. PHP 중국어 웹사이트를 지원해 주셔서 감사합니다.

Python 스크립트를 사용하여 sitemap.xml을 생성하는 방법에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!