BeautifulSoup公式サイト
requests モジュールでhtmlソースを取ってくる。
BeautifulSoup4 モジュールでソースを整形する。
Beautiful Soup 4.2.0 Doc. 日本語訳 (2013-11-19)
Beautiful Soupはpythonで動作するHTMLとXMLのパーサーです。Beautiful Soupはパースしたツリーの操作、検索、変更を簡単に、かつ、今までと同じ方法でできます。これにより、プログラマーの仕事時間を節約します。
Beautiful Soup 4 Python - PythonForBeginners.com
Beautiful Soup 4 Python will help you improve your python skills with easy to follow examples and tutorials. Click here to view code examples.
PythonでWebクローリングを行うには、主に以下2ステップを行います。
- 指定したURLのHTMLを取得する
- 取得したHTMLから必要な情報を読み込む
指定したURLからのHTML取得には、urllib.requst
を利用します
import urllib.request url= "http://www.yoheim.net/" response= urllib.request.urlopen(url) html= response.read().decode("utf-8") HTMLを取得できたら次にHTMLを解釈して必要なデータを取り出します。
from bs4import BeautifulSoup soup= BeautifulSoup(html, "html.parser") article= soup.find(class_="articleList") h2_list= article.find_all("h2") titles= [h2.string for h2in h2_list] これで値の取得ができました。手順としては以下の流れとなります。
- BeautifulSoupオブジェクトを生成する
find
やfind_all
を使って、HTML要素を取得する.string
などで値を抽出する
ここは決まり文句のようなつもりで、以下でインスタンス化できます。
soup= BeautifulSoup(html, "html.parser")
必要なHTML要素の抜き出し
HTML要素を抜き出すために、以下のような仕組みが用意されています。
### 条件に一致する要素を1つ取得する(find) # HTML要素名 h1= soup.find("h1") # クラス名 article= soup.find(class_="articleList") # ID header= soup.find(id="header_subtitle") ### 条件に一致する要素を全て取得する(find_all) # HTML要素名 h2= soup.find_all("h2") # クラス名 balls= soup.find_all(class_="ball") # ID header= soup.find_all(id="header_subtitle") # findやfind_allは連ねることもできる items= soup.find(class_="articleList").find_all("h2")
上記のメソッドを駆使して必要な要素までたどり着きます。
必要な要素までたどり着いたらあとは値を抜き出します。
# <h2>タイトルタイトル</h2> title= h2.string print(title) # => タイトルタイトル # <img src="/image/390.jpg" alt="画像"/> img= soup.find("img") src= img["src"] print(src) # => /image/390.jpg

How to scrape websites with Python and BeautifulSoup
by Justin Yek How to scrape websites with Python and BeautifulSoup There is more information on the Internet than any human can absorb in a lifetime. What you n...
コメント