LoginSignup
13
5

More than 5 years have passed since last update.

PythonでURLのリストからサイトマップ(sitemap.xml)を作る【決定版】

Last updated at Posted at 2019-01-12

Python で URL のリストからサイトマップ (sitemap.xml) を作る

SEO について考える上で、必須である項目の1つにサイトマップ(sitemap.xml)があります。そこで、URL のリストからサイトマップを作る方法についてご紹介いたします。
(※ Python 3系を前提としています)

Google の推奨するサイトマップ形式

sitemap.xml の主な構造は以下です。

<?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>
    <lastmod>2018-06-04</lastmod>
  </url>
  <url>
    <loc>http://www.example.com/faa.html</loc>
    <lastmod>2018-06-04</lastmod>
  </url>
</urlset>

参考: https://support.google.com/webmasters/answer/183668?hl=ja

sitemap.xml を作る

xmlという標準ライブラリの、ElementTreeを利用します。

サンプルプログラム

import xml.etree.ElementTree as ET

urls = [
    "https://www.yahoo.co.jp/",
    "https://www.google.com/",
    "https://www.facebook.com/",
    "https://twitter.com/",
    "https://paymap.jp/",
]

urlset = ET.Element('urlset')
urlset.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
tree = ET.ElementTree(element=urlset)

for url in urls:
    url_element = ET.SubElement(urlset, 'url')
    loc = ET.SubElement(url_element, 'loc')
    loc.text = url
    lastmod = ET.SubElement(url_element, 'lastmod')
    lastmod.text = "2019-01-12"

tree.write('sitemap.xml', encoding='utf-8', xml_declaration=True)

順番に説明

import

xmlElementTreeET としてインポートします。

import xml.etree.ElementTree as ET

urls

URL のリストを urls としました。

urls = [
    "https://www.yahoo.co.jp/",
    "https://www.google.com/",
    "https://www.facebook.com/",
    "https://twitter.com/",
    "https://paymap.jp",
]

urlset

sitemap の構造に合わせて、urlsetをルートにし、xmlns のアトリビュートをセットします。

urlset = ET.Element('urlset')
urlset.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
tree = ET.ElementTree(element=urlset)

各要素を作る

URL のリストからでurl に loclastmod を作成し、loc に URL を挿入し、lastmodには日付を挿入します。必要に応じてchangefreqなどもセットしてください。

for url in urls:
    url_element = ET.SubElement(urlset, 'url')
    loc = ET.SubElement(url_element, 'loc')
    loc.text = url
    lastmod = ET.SubElement(url_element, 'lastmod')
    lastmod.text = "2019-01-12"

日付の操作方法を詳しく知りたい場合はPython datetime 日付の計算、文字列から変換【決定版】をご覧ください。

書き出し

encodingxml_declarationで、書き出される XML 上部に<?xml version="1.0" encoding="UTF-8"?>を定義し、sitemap.xmlというファイル名で書き出します

tree.write('sitemap.xml', encoding='utf-8', xml_declaration=True)

sitemap.xml の確認

書き出されたファイルは以下のようになっています。

sitemap.xml on Editor

これでは確認しずらいので、Chromeなどのブラウザにドラッグ・アンド・ドロップすると、以下のように確認することができます。

sitemap.xml on Browser

まとめ

Python によるサイトマップ(sitemap.xml)の作り方の説明でした。

いいねをしていただけるとモチベーションに繋がりますので押していただけると嬉しいです。

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5