2019-02-27に投稿

BeautifulSoup入門 HTMLを取得して表示する【Python】

スクレイピングをしたい

Webサイトから情報をまとめてCSVでごにょごにょしたいなどにスクレイピングは便利です。
今回は、Pythonのスクレイピングによく使われるBeautifulSoupを使って勉強していきます。

HTMLを定義する

本来はURLで取得したいところですが、ここはグッとこらえてナマHTMLでいきます。

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

BeautifulSoupをインポート

from bs4 import BeautifulSoup

BeautifulSoupにHTMLを渡す

soup = BeautifulSoup(html_doc)

BeautifulSoupにHTMLを渡した結果を表示する

print(soup.prettify())

完成したコード

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
print(soup.prettify())

動くサンプル

Python3

Originally published at www.corylog.com
ツイッターでシェア
みんなに共有、忘れないようにメモ

view_list [連載] BS4でスクレイピング
第1回 BeautifulSoup入門 HTMLを取得して表示する【Python】
第2回 BeautifulSoup入門 soup.の挙動を確認する
第3回 BeautifulSoup入門 スクレイピング実践編 HTML取得まで【python】
第4回 BeautifulSoup入門 スクレイピング実践編 タイトルとリンク取得まで【python】
第5回 BeautifulSoup入門 スクレイピング実践編 複数ページに対応させる【python】

aocory

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント