URLの一覧を渡してページのタイトルをまとめて取得するスクリプトをpythonで作成しました。
プログラム
下記がスクリプトです。
データの出力形式は、最後の行のprint()で決定しており、この例だとmarkdownフォーマットで出力しています。
import os
import sys
import requests
from bs4 import BeautifulSoup
for line in sys.stdin:
# URLで無い場合は、そのまま出力
if not line.startswith('http'):
print(line)
continue
## 指定ページのタイトルを取得
url = line.replace('\n', '')
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
title = soup.find('title').text.replace('\n', '')
# output as markdown
print('- [{0}]({1})'.format(title, url))
実行例
こちらが実行結果です。
url.txtに記載されたURLの一覧を元に、各サイトのhtmlにあるtitleタグを取得して、出力しています。
$ cat url.txt
https://www.yahoo.co.jp/
https://www.google.com/
https://www.bing.com/
$ cat url.txt | python getTitle.py
- [Yahoo! JAPAN](https://www.yahoo.co.jp/)
- [Google](https://www.google.com/)
- [Bing](https://www.bing.com/)
出力の形式を変更したい場合は、先ほどのスクリプトのprint()を変更すれば良いです。
# output as markdown
print('- [{0}]({1})'.format(title, url))
↓
# youtube
print('# {0}\n{1}\n'.format(title, url))
出力のフォーマットを変更した後、再度実行してみた結果です。
$ cat youtube.txt | python create.py
$ cat url.txt | python create.py
# Yahoo! JAPAN
https://www.yahoo.co.jp/
# Google
https://www.google.com/
# Bing
https://www.bing.com/
こちらもおススメ