Python を使用してサイトマップを生成する方法の詳細な紹介

巴扎黑
リリース: 2017-08-16 13:37:59
オリジナル
2347 人が閲覧しました

Web サイトのプロジェクトに取り組む場合、サイトマップの生成にスクリプトがよく使用されます。これはクローラーにとって便利で、SEO にも有益です。 では、Python を使用してサイトマップを生成するにはどうすればよいでしょうか?以下で勉強してみましょう。

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>
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(&#39;%Y-%m-%dT%H:%M:%S+08:00&#39;, t)
  return time.strftime(&#39;%Y-%m-%dT%H:%M:%SZ&#39;, t)
ログイン後にコピー

最適化

一般に、lxml を使用すると効率が悪く、大量のメモリを消費します。ファイルの write メソッドを使用して直接作成できます。

りー

以上がPython を使用してサイトマップを生成する方法の詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!