4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでHTML解析(スクレイピング)

Last updated at Posted at 2019-09-09

サイトリニューアルのとき、よくあるデータ移行があります。
手動作業はできますが、コストかかりますので、
バッチでHTML取得⇒解析⇒新システムに投入 というような機能が役に立つ場合があります。

Javaでは、jsoupというライブラリは有名です。
Pythonでは、beautifulsoup4 というライブラリは有名です。

jsoup: https://jsoup.org/
beautifulsoup4: https://pypi.org/project/beautifulsoup4/

VSCodeのターミナルからインストール

pip install beautifulsoup4

HTMLのfragmentの解析

解析サンプル

from bs4 import BeautifulSoup

html = "<body><h1>PythonでHTML解析</h1><p>HTML解析の説明</p></body>"
soup = BeautifulSoup(html, "html5lib")
print(soup.h1)

結果

<h1>PythonでHTML解析</h1>

一点注意したいのは、ライブラリにあるファイルを自分のプロジェクトフォルダーに作成するとエラーになる可能性があります。
例えば、「bs4.py」というファイルを作成して実行しようとするとエラーです。

URLから解析

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("https://news.yahoo.co.jp/").read()

soup = BeautifulSoup(html, 'html.parser')

# print(soup.prettify())
# css-selectorを書く
elements = soup.select(".topicsList li.topicsListItem a")
for element in elements:
    print("title: " + element.text + ", href: " + element.get("href"))

解析結果

title: 日産・西川社長 16日付で辞任, href: https://news.yahoo.co.jp/pickup/6336028
title: 日産社長退任 裏に激しい攻防, href: https://news.yahoo.co.jp/pickup/6336027
title: 停電続く千葉「耐えるしか」, href: https://news.yahoo.co.jp/pickup/6336024
title: 上皇后さま 術後の経過順調, href: https://news.yahoo.co.jp/pickup/6336026
title: ヤマト 住所なしで発送可能に, href: https://news.yahoo.co.jp/pickup/6336019
title: 経費削減 減りゆくテレビCM, href: https://news.yahoo.co.jp/pickup/6335992
title: 騒然 ロッテ井口監督が即退場, href: https://news.yahoo.co.jp/pickup/6336025
title: 3選手がメッシとの会話拒否か, href: https://news.yahoo.co.jp/pickup/6336029

詳しい情報のURL:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

以上

4
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?