Python で HTML のタイトルを取得する

published: 2019.04.08 / modified:

Python で HTML ソースのタイトル(title 要素のテキスト)を取得する。

正規表現を使って取得する

以下の例では、 re モジュールの search() メソッドを使用。

import re

html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>タイトル</title>
</head>
<body>
<h1>見出し</h1>
</body>
</html>
"""

title = re.search('(?<=<title>).*(?=</title>)', html)

if title:
    print(title.group()) # タイトル

Previous Article

Next Article