やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

PythonでのWebスクレイピング環境構築(chromium-driver,selenium,beautifulsoup4)

 あっさりできた。

成果物

情報源

必要なライブラリのインストール

 これでJavaScriptで生成されるサイトも表示できるらしい。

sudo apt install chromium-driver
pip3 install selenium
pip3 install beautifulsoup4

詳細ログ

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
注意、'chromium-driver' の代わりに 'chromium-chromedriver' を選択します
以下のパッケージが自動でインストールされましたが、もう必要とされていません:
  docutils-common docutils-doc gir1.2-vte-2.90 libnunit-cil-dev libnunit-console-runner2.6.3-cil libnunit-core-interfaces2.6.3-cil
  libnunit-core2.6.3-cil libnunit-framework2.6.3-cil libnunit-mocks2.6.3-cil libnunit-util2.6.3-cil libvte-2.90-9 libvte-2.90-common
  libvte-2.90-doc python-alabaster python-babel python-babel-localedata python-docutils python-imagesize python-pygments python-roman
  python-tz rlwrap sphinx-common vim-runtime
これを削除するには 'sudo apt autoremove' を利用してください。
以下のパッケージが新たにインストールされます:
  chromium-chromedriver
アップグレード: 0 個、新規インストール: 1 個、削除: 0 個、保留: 0 個。
3,781 kB のアーカイブを取得する必要があります。
この操作後に追加で 12.1 MB のディスク容量が消費されます。
取得:1 http://mirrors.ustc.edu.cn/archive.raspberrypi.org/debian stretch/main armhf chromium-chromedriver armhf 72.0.3626.121-0+rpt4 [3,781 kB]
3,781 kB を 14秒 で取得しました (265 kB/s)                                                                                             
以前に未選択のパッケージ chromium-chromedriver を選択しています。
(データベースを読み込んでいます ... 現在 149496 個のファイルとディレクトリがインストールされています。)
.../chromium-chromedriver_72.0.3626.121-0+rpt4_armhf.deb を展開する準備をしています ...
chromium-chromedriver (72.0.3626.121-0+rpt4) を展開しています...
chromium-chromedriver (72.0.3626.121-0+rpt4) を設定しています ...
Collecting selenium
  Using cached https://files.pythonhosted.org/packages/80/d6/4294f0b4bce4de0abf13e17190289f9d0613b0a44e5dd6a7f5ca98459853/selenium-3.141.0-py2.py3-none-any.whl
Collecting urllib3 (from selenium)
  Using cached https://files.pythonhosted.org/packages/e6/60/247f23a7121ae632d62811ba7f273d0e58972d75e58a94d329d51550a47d/urllib3-1.25.3-py2.py3-none-any.whl
Installing collected packages: urllib3, selenium
Successfully installed selenium-3.141.0 urllib3-1.25.3
Collecting beautifulsoup4
  Using cached https://files.pythonhosted.org/packages/1a/b7/34eec2fe5a49718944e215fde81288eec1fa04638aa3fb57c1c6cd0f98c3/beautifulsoup4-4.8.0-py3-none-any.whl
Collecting soupsieve>=1.2 (from beautifulsoup4)
  Using cached https://files.pythonhosted.org/packages/0b/44/0474f2207fdd601bb25787671c81076333d2c80e6f97e92790f8887cf682/soupsieve-1.9.3-py2.py3-none-any.whl
Installing collected packages: soupsieve, beautifulsoup4
Successfully installed beautifulsoup4-4.8.0 soupsieve-1.9.3

コード

 指定したURLを指定したパスに保存する。

download_html.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import extractcontent3
import sys
import os

if len(sys.argv) < 2:
    raise Error('第1引数にURLパスを指定してください。')
    exit()
url = sys.argv[1]
path_html = sys.argv[2] if 2 < len(sys.argv) else '/tmp/work/index.html'

options = Options()
options.set_headless(True)
driver = webdriver.Chrome(chrome_options=options)
driver.get(url)
html = driver.page_source.encode('utf-8')
print(html)
soup = BeautifulSoup(html, "html.parser")

os.makedirs(os.path.dirname(path_html), exist_ok=True)
with open(path_html, mode='w') as f:
    f.write(str(html))

 実行コマンドは以下。

python3 a.py URL 出力先HTMLパス

 できた。

ちょっとハマった

 出力時にstr(html)として文字列化してやらないと以下エラーがでる。

Traceback (most recent call last):
  File "a.py", line 29, in <module>
    f.write(html)
TypeError: write() argument must be str, not bytes

 つまり、driver.page_source.encode('utf-8')で取得された結果はバイナリデータということ。

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux