武器商人@Pythonのブログ

Pythonを好んで使っているプログラマです。Pythonこそが最強のプログラミング言語だと思っています。Pythonは使いやすいです。Pythonは書きやすいです。Pythonは読みやすいです。Pythonはパワフルです。Pythonは一貫性があります。Pythonが好きです。

ウェブサイトのtitleタグを正規表現を使い取得する

スポンサーリンク

私の以下3サイトのtitleタグを取得するスクリプトを書きました。
或阿呆のブログ
武器商人@Pythonのブログ
http://oneshotlife-excel-vba.hateblo.jp/

やりかたはいろいろあるんですが、今回は、正規表現で、titleタグをマッチさせるやり方で取得しました。

サンプルコード

# -*- coding: utf-8 -*-
import urllib
import re

urls = ["http://oneshotlife-tom.hatenadiary.jp/",
        "http://oneshotlife-python.hatenablog.com/",
        "http://oneshotlife-excel-vba.hateblo.jp/"]

for url in urls:
    html = urllib.urlopen(url)
    htmltext = html.read()
    pattobj = re.compile('<title>(.*?)</title>')
    matchobj = pattobj.search(htmltext)
    rettxt = matchobj.group(0).decode('utf-8')
    title = rettxt.replace("<title>","")
    title = title.replace("</title>","")
    print title

実行結果

或阿呆のブログ
oneshotlife-pythonのブログ
Excel VBAのサンプルコード

Web Scraping with Python: Collecting Data from the Modern Web

Web Scraping with Python: Collecting Data from the Modern Web