Pythonのライブラリ(Beautiful Soup)を利用してスクレイピングしてみた
インストールとタグ操作
root@hostname:/home/shimizu/python# aptitude install python-bs4
以下の新規パッケージがインストールされます:
python-bs4 python-chardet{a} python-lxml{a}
...
root@hostname:/home/shimizu/python# cat scraping-bs4.py
# coding: UTF-8
import urllib2
from bs4 import BeautifulSoup
res = urllib2.urlopen("http://ll.jus.or.jp/2014/program.html")
# オブジェクト<class 'bs4.element.ResultSet'>を取得し、listのように扱える
soup = BeautifulSoup(res.read())
# 先頭のタグを表示する
print soup.find('a')
# タグ内の属性を表示する
print soup.a.get('href')
# タグの中の文字を取得する
print soup.a.string
root@hostname:/home/shimizu/python# python scraping-bs4.py
<a href="index.html" rel="home">LL Diver</a>
index.html
LL Diver
すべてのaタグの要素を表示する
root@hostname:/home/shimizu/python# cat scraping-bs4-2.py
# coding: UTF-8
import urllib2,sys
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup
res = urllib2.urlopen("http://ll.jus.or.jp/2014/program.html")
# オブジェクト<class 'bs4.element.ResultSet'>を取得し、listのように扱える
soup = BeautifulSoup(res.read())
# リンク抽出
for link in soup.find_all('a'):
if link.string is not None:
print link.string + ": " + link.get('href')
root@hostname:/home/shimizu/python# python scraping-bs4-2.py
LL Diver: index.html
検索: index.html%3Fp=49.html#search-container
コンテンツへ移動: index.html%3Fp=49.html#content
LL Diver: index.html
LL Diver開催案内: index.html%3Fp=9.html
プログラム: index.html%3Fp=49.html
タイムテーブル: index.html%3Fp=198.html
アンケート: index.html%3Fp=260.html
アーカイブ: index.html%3Fp=77.html
昼の部: index.html%3Fp=49.html#day
...
その他操作
root@hostname:/home/shimizu/python# python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2,sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf-8')
>>> from bs4 import BeautifulSoup
>>> res = urllib2.urlopen("http://ll.jus.or.jp/2014/program.html")
>>> soup = BeautifulSoup(res.read())
>>> print soup.title
<title>プログラム | LL Diver</title>
>>> print soup.title.name
title
>>> print soup.title.string
プログラム | LL Diver
>>> soup.p
<p>LL Diverのプログラムは、<a href="index.html%3Fp=49.html#day">昼の部</a>・<a href="index.html%3Fp=49.html#night">夜の部</a>に分けて行います。<br/>
<a href="index.html%3Fp=198.html" target="_blank" title="タイムテーブル">タイムテーブル</a>もあわせてご覧ください。</p>
>>> print soup.find(id="genericons-css")
<link href="wp-content/themes/twentyfourteen/genericons/genericons.css%3Fver=3.0.2.css" id="genericons-css" media="all" rel="stylesheet" type="text/css"/>
### タグを除去して全テキストを抽出 ###
>>> print(soup.get_text())
...
### soupについて ###
>>> print type(soup)
<class 'bs4.BeautifulSoup'>
>>> print soup.prettify
...
### Tag obj ###
>>> type(soup)
<class 'bs4.BeautifulSoup'>
>>> type(tag)
<class 'bs4.element.Tag'>
>>> tag.name
'a'
### 辞書にアクセスする ###
>>> tag.attrs
{'href': 'index.html', 'rel': ['home']}
### classは予約後のため class_ というキーワード引数でCSSのクラスを検索 ###
>>> soup.find_all(class_="page_item page-item-9")
[<li class="page_item page-item-9"><a href="index.html%3Fp=9.html">LL Diver開催案内</a></li>]
実際にデータを取得する-天気予報データ-
Python で簡単なテキスト処理 (3) – Beautiful Soup を使ってスクレイピング
http://jutememo.blogspot.jp/2008/06/python-3-beautiful-soup.html
より拝借
root@hostname:/home/shimizu/python# cat scraping-bs4-3.py
# coding: UTF-8
import urllib2,sys
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup
URL = "http://www.data.jma.go.jp/obd/stats/etrn/view/daily_s1.php?prec_no=44&prec_ch=%93%8C%8B%9E%93s&block_no=47662&block_ch=%93%8C%8B%9E&year=2008&month=01&day=12&view=p1"
# 出力する日付
DATE_FROM = 1
DATE_TO = 5
# データ取得
res = urllib2.urlopen(URL)
soup = BeautifulSoup(res.read())
#print soup.prettify
#print type(soup)
records = []
# class 属性が mtx である tr タグを対象に
for tr in soup('tr',{'class':'mtx'}):
rec = []
# id 属性がp_print のdivタグを対象に
for div in tr('div',{'class':'a_print'}):
# a タグを対象に
for a in div('a'):
# 日付を取得
rec.append(a.renderContents())
# class 属性が data_0_0 である td タグを対象に
for td in tr('td',{'class':'data_0_0'}):
# 各データを取得
data = td.renderContents().strip()
rec.append(data)
if rec != []: records.append(rec)
# 取得したデータを出力
for rec in records:
# 指定された日付の期間以外は出力しない
if int(rec[0]) not in range(DATE_FROM, DATE_TO + 1): continue
for i,data in enumerate(rec):
if i in [1,6]: print unicode(data, 'utf-8'), "\t",
print
root@hostname:/home/shimizu/python# python scraping-bs4-3.py
998.7 6.0
1007.2 6.2
1011.6 5.9
1014.6 7.0
1014.0 6.0
root@hostname:/home
実際にデータを取得する-宅配便の配送状況-
Pythonでスクレイピング
http://i2bskn.hateblo.jp/entry/20120820/1345478918
より拝借
root@hostname:/home/shimizu/python# cat scraping-bs4-4.py
# coding: UTF-8
import urllib,urllib2,sys,re
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup
def kuroneko_check(n):
r = re.compile(r'>([^<]+)<br')
url = "http://toi.kuronekoyamato.co.jp/cgi-bin/tneko"
data = urllib.urlencode({"number00": "1", "number01": n})
#html = urllib2.urlopen(url,data).read().decode('shift_jis').encode('utf-8')
html = urllib2.urlopen(url,data).read()
soup = BeautifulSoup(html)
#print soup.prettify
s = str(soup.find_all("td",class_="ct")[0].font)
return r.findall(s)[0]
print(kuroneko_check('4320-xxxx-xxxx'))
root@hostname:/home/shimizu/python# python scraping-bs4-4.py
配達完了
実際にデータを取得する-文章を抽出する-
第3回 スクレイピングにチャレンジ! (2/3)
http://itpro.nikkeibp.co.jp/article/COLUMN/20080407/298191/?ST=develop&P=2
より拝借
root@hostname:/home/shimizu/python# cat scraping-bs4-5.py
# coding: UTF-8
import urllib2,sys
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup,NavigableString
url = 'http://www.linux.or.jp/'
html = urllib2.urlopen(url).read()
soup = BeautifulSoup(html)
def printText(tags):
for tag in tags:
if tag.__class__ == NavigableString:
print tag,
else:
printText(tag)
print ""
printText(soup.findAll("p"))
root@hostname:/home/shimizu/python# python scraping-bs4-5.py
すぐに使えるリナックスチュートリアルをご紹介
最新のlinuxニュースやインタビュー記事をお届けします。
30週連続企画:今週はShuah Khan氏の仕事場に潜入!
続きを読む...
...
実際にデータを取得する-ニュースサイト-
BeautifulSoup実践 -pythonで超カンタンにスクレイピング
http://d.hatena.ne.jp/lolloo-htn/20090128/1233155734
より拝借
root@hostname:/home/shimizu/python# cat scraping-bs4-6.py
# coding: UTF-8
import urllib2,sys
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup,NavigableString
url = "http://www.yomiuri.co.jp/sports/"
# データ取得
res = urllib2.urlopen(url)
soup = BeautifulSoup(res.read())
def printText(tags):
for tag in tags:
if tag.__class__ == NavigableString:
print tag
else:
printText(tag)
for data in soup('span',{'class':'headline'}):
printText(data)
root@hostname:/home/shimizu/python# python scraping-bs4-6.py
国際陸連が不正の証拠隠蔽か…ドーピング疑惑
(2015年08月16日 21時52分)
興南、2点差から粘り…鳥羽に逆転勝ちで8強
(2015年08月16日 18時34分)
2か月ぶり先発のG・大竹、1失点も白星ならず
(2015年08月16日 18時27分)
...
参考URL
PythonとBeautiful Soupでスクレイピング
http://qiita.com/itkr/items/513318a9b5b92bd56185
Beautiful Soup
http://kondou.com/BS4/
Python で簡単なテキスト処理 (3) – Beautiful Soup を使ってスクレイピング
http://jutememo.blogspot.jp/2008/06/python-3-beautiful-soup.html
Pythonでスクレイピング
http://i2bskn.hateblo.jp/entry/20120820/1345478918
スクレイピングまとめ
http://matome.naver.jp/odai/2136441394137974201