LoginSignup
7
9

More than 5 years have passed since last update.

ラズパイでスクレイピングする時の詰みポイント

Posted at

きっかけ

通っている学校のホームページで授業変更を確認するけど、毎回見に行くのがだるい。
Python2系でスクレイピングしてラズパイにLINEで通知してもらう。

現状

スクレイピングには成功したけど、文字コードの問題でLINEに送信できなくて詰んでる。
それよりも前の段階で何回も詰みかけたので、他の人のヒントになればと思い書いた。

詰みポイント1

モジュールインポートで詰む

ソースコードの一部を以下に示す。

jugyohenko.py(一部抜粋)
#授業変更を取得する
#coding:utf-8
import urllib
from bs4 import BeautifulSoup
from linebot import LineBotApi
from linebot.models import TextSendMessage

3行目「import urllib」だが、スクレイピング方法をググりながらコーディングしてると、Python2系と3系で記述方法が異なるため、なんかうまくいかなくなることがあった。3系だと各モジュールが分割されたため、「import urllib.request」と書く。が、今回は2系で作るので、3行目のように書く。
urllib — URL による任意のリソースへのアクセス

詰みポイント2

lxmlが無くて詰む

スクレイピングするなら、以下のソースコードはみたことがあると思う。

jugyohenko.py(一部抜粋)
url="XXXXXXXXXXXXXXXXXXXXXXXXX"
html=urllib.urlopen(url).read()
soup=BeautifulSoup(html,"lxml")

Windowsで実行した時は普通に動作したので、「よし!いける!」何も考えずにラズパイに移して実行!!

ERROR
Traceback (most recent call last):
  File "/home/pi/jugyohenko.py", line 65, in <module>
    soup=BeautifulSoup(html,"lxml")
  File "/usr/local/lib/python2.7/dist-packages/bs4/__init__.py", line 165, in __init__
    % ",".join(features))
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

IMG_4066.JPG
lxmlがないとか言われてるっぽいので入れる。
「pip install lxml」等でうまくいかなかったので本当にくじけそうだった。
以下に解決したコマンドを示す。

pi@raspberrypi:~ $ sudo apt-get install python-lxml

で、入ったか確認してみる

pi@raspberrypi:~ $ pip freeze | grep -e request -e lxml -e beautiful
beautifulsoup4==4.6.0
lxml==3.4.0
requests==2.4.3

あ。入ってる。
IMG_5564.JPG
あとは、文字コードの謎を解明すれば授業変更お知らせボットが完成するZOY!(白目)

7
9
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
7
9