Python1.Beautiful Soupを使う方法

「プログラミング」及び「開発」関連用語集

カテゴリー: クローラ  閲覧数:358 配信日:2017-03-02 21:49


Beautiful Soup


Pythonモジュール
・HTMLを構文解析して要素の指定を手助けしてくれる
・要素を指定して、値を抽出


コード例


▼HTML
<html>
 <head>
   <meta charset='utf-8' />
 </head>
 <body>
   <h1>クローリングとスクレイピング</h1>
   <div id="articleInfo">
     <p>
       <span class="timestamp">2017-3-2 21:15:35</span>
       <span class="author"><a href="http://programming-term.w4c.work/">プログラミング用語</a></span>
     </p>
   </div>
   <div id="articleText">
     ウェブサイトのクローリングとスクレイピングについて  

   </div>
 </body>
</html>


▼Python
#coding: utf-8
from bs4 import BeautifulSoup
from datetime import datetime

#変数htmlには上記のHTMLがstrで代入されているとします。
soup = BeautifulSoup(html)

#変数title, timestamp, author, author_link, bodyにそれぞれタイトル、投稿日時、著者、著者のリンク、記事本文が代入されます。
title = soup.h1.find(text=True)
timestamp = soup.find(id='articleInfo').find(class_='timestamp').find(text=True)
author = soup.find(id='articleInfo').find(class_='author').find('a').find(text=True)
author_link = soup.find(id='articleInfo').find(class_='author').find('a').get('href')
body = soup.find(id='articleText').find(text=True)