LoginSignup
3
4

More than 5 years have passed since last update.

Webスクレイピング

Last updated at Posted at 2019-02-28

インストール

Beautifulsoupとurllibをインストールしましょう。

pip3 install beautifulsoup
pip3 install urllib3

インポート

次にインストールしたモジュールをインポートします。

# coding: UTF-8
import urllib.request, urllib.error
from bs4 import BeautifulSoup

htmlの取得

つづいて、htmlを取得したいurlを指定します。今回は日本経済新聞のウェブサイトを指定します。
そのあとにBeautifulSoupで扱える形にします。

url = "https://www.nikkei.com/"
html = urllib.request.urlopen(url)
soup = BeautifulSoup(html, 'html.parser')

このsoupには、全htmlが格納されています。

特定の情報の取得

いよいよ、情報を取得していきます。

titleを取得

soup.find("head").find("title") 
もしくは
soup.find("title")

h1を取得(最初に出てきたタグのみ)

soup.find("body").find("h1")
もしくは
soup.find("h1")

#textを取得
soup.find("body").find("h1").text

h1のタグをすべて取得

上記の場合、最初に出てきたタグしか出てこない。なので、すべてのタグを取得するには以下のように書く

soup.find_all("h1")

#リストとして取得するには[]で囲む
h1s = soup.find_all(["h1"])

#テキストを取得するにはforで回す
h1s = soup.find_all(["h1"])
for h1 in h1s:
 print(h1.text)
3
4
0

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
3
4