shunbourianの日記

SEをやっているリーマンのブログ。好きなお酒とか、読んだ本とか、いろいろ。

Python3でWebスクレイピング

Python3を使ったWebページのタイトルの取得方法

 Python2.XでのWebスクレイピング方法と3.X系でのimportするモジュールが違うので

メモ。

以下のコードを実行する前に、BeautifulSoupをインストールしておくこと。

$ pip install beautifulsoup4


コードは以下。

# python3では以下をimportする 
import urllib.request
import bs4

# スクレイピングしたいWeb PageのURLをセット
# 下記はSRAMのウィキページ
url = "https://ja.wikipedia.org/wiki/Static_Random_Access_Memory"

# htmlを取得
get_html = urllib.request.urlopen(url)

# 取得したhtmlからタグをパースする
bs_soup = bs4.BeautifulSoup(get_html, "html.parser")

# htmlからタイトルタグを抽出
tag_title = bs_soup.title
title = tag_title.string

# タイトルタグとタイトルの文字列を表示
print(tag_title)
print(title)

 

結果は以下の通り。

# print(tag_title)
<title>Static Random Access Memory - Wikipedia</title>

# print(title)
Static Random Access Memory - Wikipedia