備忘録。
目的
まずは、なぜスクレイピングをやってみたくなったのかの理由について。
自然言語処理を行うにあたって、現在は写経等を繰り返し、用意された整ったデータを利用しているが、そろそろ生のデータを扱ってみたくなったため。
いろいろなサイトを調べてみたけど、パーサーを指定するための書式をうまく見つけられなかったので、書式を残す意味合いで。
まずは、小さなサンプル的な処理から。
次のブログを参考にしました。ありがとうございます。
https://runble1.com/scraping-beautifulsoup/
http://hideharaaws.hatenablog.com/entry/2016/05/06/175056
環境は、
Windows10 (Bash on Ubuntu on Windows)
python3.6
anaconda3-5.0.1
jupyter notebook
ではさっそく、
$ pip install beautifulsoup4
$ pip install lxml
$ pip install cssselect
成功。
簡単に調べてみると、「beautifulsoup4」が根本的に必要なもののようで、「lxml」と「cssselect」は、拡張機能のような感じ。
ソースコートは、参考サイトほぼそのままですが、パーサー(lxmlなど)の指定が重要っぽいので、いくつか試してみる。
パーサーの指定
まずはエラーが出るパターン。パーサの指定なし。
# https://runble1.com/scraping-beautifulsoup/
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read())#Y エラーがでるパターン。
print(bsObj.h1)#h1タグで挟まれた部分の出力
# 出力結果
# The code that caused this warning is on line 193 of the file /home/*****/.pyenv/versions/anaconda3-5.0.1/lib/python3.6/runpy.py. To get rid of this warning, change code that looks like this:
# BeautifulSoup(YOUR_MARKUP})
# to this:
# BeautifulSoup(YOUR_MARKUP, "lxml")
# markup_type=markup_type))
次にエラーが出ないパターン。パーサの指定あり。
# https://runble1.com/scraping-beautifulsoup/
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read(), "lxml")
# bsObj = BeautifulSoup(html.read(),"html.parser")#これもOK。
# bsObj = BeautifulSoup(html.read(), "html5lib")#これもOK。
print(bsObj.h1)#h1タグで挟まれた部分の出力
# 出力結果
# <h1>An Interesting Title</h1>
以上。