こんにちは。KOUKIです。
SEO対策で自分のサイトから特定の情報を抜き出して、ファイルに保存したいことってありませんか?
Pythonで、ブログの「url」,「title」,「description」を抜き出すブログ情報取集ツールを作成しました^^
本記事は、ブログ情報取集ツールの紹介になります。
<こんな方向け>
・ 自分が運営するブログのメタ情報を自動収集したい人
・ ブログ作業の自動化方法を検討している人
<目次>
免責事項
ブログ情報取集ツールは、あくまでサンプルであり、動作保証していません。また、ご使用される場合は、必ず「自分のサイト」で使ってください。このソースコードを実行して何らかの問題が発生した場合でも、責任は負いかねますので、ご了承ください。
こんな情報を集める
下記のキャプチャは、ブログ情報取集ツールの収集結果(csv)をGoogleスプレッドシートに表示させたものです。

ちょっと見えづらいと思いますが、左から「url」、「title」、「description」と収集した情報が並んで表示されています。
使用例
・title、descriptionがSEO対応になっているか調べたい
・パーマリンクが適切な設定になっているか調べたい
動作確認環境
このスクリプトを実行するには、次の前提条件があります。
Python
Pythonをローカルにインストールします。
インストール方法※超簡単です
モジュール
pythonをインストール後、下記のモジュールもインストールしてください。
1 2 |
pip install requests pip install beautifulsoup4 |
サイトマップ
当ブログでは、Wordperss + Google XML Sitemapsを使ってsitemap.xmlを作成しました。
※他のサイトマップでも動くかもしれません
ブログ情報収集ツールの挙動
ブログ情報取集ツールは、私のsitemap.xmlの構造に合わせて作成しています。
「https://selfnote.work/sitemap.xml」
私のsitemap.xmlは、第一階層に次のurlが存在します。
※2019年10月現在
1 2 3 4 5 6 |
https://selfnote.work/sitemap-misc.xml https://selfnote.work/sitemap-tax-category.xml https://selfnote.work/sitemap-pt-post-2019-10.xml https://selfnote.work/sitemap-pt-post-2019-09.xml https://selfnote.work/sitemap-pt-post-2019-08.xml https://selfnote.work/sitemap-pt-page-2019-08.xml |
上記のurlのうち、「post」がついているurlの情報からブログ情報を抜き取っています。
post付きのurlをクリックしていただくと分かると思いますが、そこに投稿した記事のurlが格納されています。
サンプルコード
次のサンプルコードをDesktop上に「selfnote_webinfo.py」のファイル名で保存してください。
※ファイル名はなんでも構いません。
No. | バージョン | 備考 |
---|---|---|
1 | Ver1 | 新規作成 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# ====================================================================== # File Name : selfnote_webinfo.py # Creation Date : 2019/10/3 # Update Date : # # Copyright <2019> selfnote. All rights reserved. # ====================================================================== import csv import requests from bs4 import BeautifulSoup def get_url(url, tag): r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') sitemap_tags = soup.find_all(tag) if tag == 'sitemap': print("The number of sitemaps are {0}".format(len(sitemap_tags))) else: print("The number of urls are {0}".format(len(sitemap_tags))) xml_list = [] for sitemap in sitemap_tags: xml_list.append(sitemap.findNext("loc").text) return xml_list def save_meta_info(url_list): meta_info_list = [] for url in url_list: r = requests.get(url) html = BeautifulSoup(r.text, 'html.parser') metas = html.find_all('meta') meta_info_list.append({ 'url': url, 'title': html.find('h1').text, 'description': [meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description' ]}) with open('metainfo.csv', 'a', newline='') as csv_file: fileheader = ['url', 'title', 'description'] writer = csv.DictWriter(csv_file, fieldnames=fileheader) writer.writeheader() for meta_info in meta_info_list: writer.writerow(meta_info) return if __name__ == '__main__': # Here is your site map url sitemap_url = 'https://hogehoge/sitemap.xml' xml_list = get_url(sitemap_url, 'sitemap') url_list = [] for xml in xml_list: if 'post' in xml: url_list += get_url(xml, 'url') save_meta_info(url_list) |
実行方法
ソースコードの以下の部分を自分のサイトマップのurlに変更してください。
1 |
sitemap_url = 'https://hogehoge/sitemap.xml' |
コマンドライン上で、以下のコマンドを実行してください。
1 |
python selfnote_webinfo.py |
ソースファイルを格納した場所に、「metainfo.csv」が実行されます。
サンプルコードの作り方
サンプルコードの作り方も載せておきます。興味のある方や動作に不安がある方は、確認しておいてください。
※サンプルコードVer1の作り方です。サンプルコードは更新されますが、作り方は更新しません
まずは、「https://selfnote.sitemap.xml」から第一階層のurl一覧を取り出します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from bs4 import BeautifulSoup import requests def getSitemapInfo(url)->list: r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') sitemap_tags = soup.find_all("sitemap") print("The number of sitemaps are {0}".format(len(sitemap_tags))) xml_list = [] for sitemap in sitemap_tags: xml_list.append(sitemap.findNext("loc").text) return xml_list if __name__ == '__main__': xml_list = getSitemapInfo('https://selfnote.work/sitemap.xml') for xml in xml_list: print(xml) |
このファイルを実行してみます。
1 2 3 4 5 6 7 |
The number of sitemaps are 6 https://selfnote.work/sitemap-misc.xml https://selfnote.work/sitemap-tax-category.xml https://selfnote.work/sitemap-pt-post-2019-10.xml https://selfnote.work/sitemap-pt-post-2019-09.xml https://selfnote.work/sitemap-pt-post-2019-08.xml https://selfnote.work/sitemap-pt-page-2019-08.xml |
sitemapのxmlが取得できましたね。
次にブログのurl一覧を取得します。
私の場合は、「post」の文字列が入ったurlから情報を取得します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
from bs4 import BeautifulSoup import requests def getSitemapInfo(url)->list: r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') sitemap_tags = soup.find_all("sitemap") print("The number of sitemaps are {0}".format(len(sitemap_tags))) xml_list = [] for sitemap in sitemap_tags: xml_list.append(sitemap.findNext("loc").text) return xml_list def get_url(url) -> list: r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') url_tags = soup.find_all('url') print("The number of urls are {0}".format(len(url_tags))) url_list = [] for url in url_tags: url_list.append(url.findNext('loc').text) return url_list if __name__ == '__main__': # サイトマップ一覧を取得する xml_list = getSitemapInfo('https://selfnote.work/sitemap.xml') url_list = [] for xml in xml_list: # htmlにpostが含まれているページのみ # 例) https://selfnote.work/sitemap-pt-post-2019-09.xml if 'post' in xml: url_list += get_url(xml) print(url_list) |
これでひとまず、サイト内のURL全てが取得できるようになりました。
1 2 3 4 5 6 |
The number of sitemaps are 6 The number of urls are 3 The number of urls are 53 The number of urls are 36 ['https://selfnote.work/20191003/programming/golang-beego-basic1/', 'https://selfnote.work/20191003/jobchange/propose-career-path/', 'https://selfnote.work/20191002/investment/rakurap-201909/', 'https://selfnote.work/20191001/programming/golang-beego-environment/', 'https://selfnote.work/20191001/investment/america-etf-201909/', 'https://selfnote.work/20190930/jobchange/receive-job2/', 'https://selfnote.work/20190930/investment/ideco-operatiion ... |
リファクタリングします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from bs4 import BeautifulSoup import requests def get_url(url, tag)->list: r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') sitemap_tags = soup.find_all(tag) if tag == 'sitemap': print("The number of sitemaps are {0}".format(len(sitemap_tags))) else: print("The number of urls are {0}".format(len(sitemap_tags))) xml_list = [] for sitemap in sitemap_tags: xml_list.append(sitemap.findNext("loc").text) return xml_list if __name__ == '__main__': # サイトマップ一覧を取得する xml_list = get_url('https://selfnote.work/sitemap.xml', 'sitemap') url_list = [] for xml in xml_list: # htmlにpostが含まれているページのみ # 例) https://selfnote.work/sitemap-pt-post-2019-09.xml if 'post' in xml: url_list += get_url(xml, 'url') print(url_list) |
次に、URLからtitleとdescriptionを抜き取り、CSV形式で保存します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import csv import requests from bs4 import BeautifulSoup def get_url(url, tag)->list: r = requests.get(url) xml = r.text soup = BeautifulSoup(xml, 'html.parser') sitemap_tags = soup.find_all(tag) if tag == 'sitemap': print("The number of sitemaps are {0}".format(len(sitemap_tags))) else: print("The number of urls are {0}".format(len(sitemap_tags))) xml_list = [] for sitemap in sitemap_tags: xml_list.append(sitemap.findNext("loc").text) return xml_list def save_meta_info(url_list): meta_info_list = [] for url in url_list: r = requests.get(url) html = BeautifulSoup(r.text, 'html.parser') metas = html.find_all('meta') meta_info_list.append({ 'url': url, 'title': html.find('h1').text, 'description': [meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description' ]}) with open('metainfo.csv', 'a', newline='') as csv_file: fileheader = ['url', 'title', 'description'] writer = csv.DictWriter(csv_file, fieldnames=fileheader) writer.writeheader() for meta_info in meta_info_list: writer.writerow(meta_info) return if __name__ == '__main__': # サイトマップ一覧を取得する xml_list = get_url('https://selfnote.work/sitemap.xml', 'sitemap') url_list = [] for xml in xml_list: # htmlにpostが含まれているページのみ # 例) https://selfnote.work/sitemap-pt-post-2019-09.xml if 'post' in xml: url_list += get_url(xml, 'url') save_meta_info(url_list) |
合わせて知っておきたい便利ツール
おわりに
ブログのメンテナンス作業ほど、大変なことはありませんよね。
記事数が増えれば増えるほど管理が大変になっていきます。
そういう煩わしいことは、プログラムに任せて、ガンガン楽しましょう^^
ブログ収取ツールは、簡単なプログラムでしたが、将来的にはGoogle Homeと連携して、音声で情報を抜き取ってくるアプリケーションを作っていく予定です。
「こういう機能が欲しい」という方がいれば、コメントください。
コメントを残す
コメントを投稿するにはログインしてください。