LoginSignup
0
1

More than 3 years have passed since last update.

【メモ】BeautifulSoup4の使い方(1) htmlを表示

Posted at

jupyternotebook上でBeautifulSoupを用いてスクレイピングする。

In[1]BeautifulSoupをimportする

In[1]
from bs4 import BeautifulSoup

In[2]スクレイピングしたい記事のhtmlを変数kijiに格納する

In[2]
kiji = """<html>
        <head>
           <title>Qiitaに投稿してみた</title>
        </head>
        <body>
           <p class="title">
              <b>アウトプットのためQiitaに挑戦。</b>
           </p>
        <p class="article">
              <b>頑張って記事を書きます。</b>
           </p>
        </body>
   </html>"""

格納したいhtmlは"""と"""の間に書く。

In[3]先ほど変数kijiに格納したhtmlをBeautifulSoupに読み込ませる。

In[3]
soup = BeautifulSoup(kiji,"html.parser")

BeautifulSoup(格納したhtmlの入っている変数,"使いたいパーサー(解析器)")と書く。今回は(kiji,"html.parser")である。パーサーは""で囲むことやhtmlparserというように.を書き忘れないことに気を付ける。

In[4]soupをprettifyと一緒に使うことで見やすく表示させる。

In[4]
print(soup.prettify())

prettify()を使うことで階層化されて見やすくなる。

In[4]出力結果

In[4]
<html>
 <head>
  <title>
   Qiitaに投稿してみた
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    アウトプットのためQiitaに挑戦。
   </b>
  </p>
  <p class="article">
   <b>
    頑張って記事を書きます。
   </b>
  </p>
 </body>
</html>

In[5]タイトルを表示させる

In[5]
print(soup.html.head.title)
In[5]出力結果
<title>Qiitaに投稿してみた</title>
0
1
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
0
1