LoginSignup
2
5

More than 3 years have passed since last update.

Raspberry Pi - Firefoxでヘッドレスとプロファイルを使ってPythonでスクレイピングする

Last updated at Posted at 2020-09-27

目標

Firefoxでヘッドレスとプロファイルを使ってPythonでスクレイピングする。
ちなみにRaspberry Pi zeroではチップがARM6なのでこのやり方では動作しない。

環境

Raspberry Pi 3 model B+
OS: Raspberry Pi OS
Python3.7

Chromeではダメなわけ

Chromeではヘッドレスモードでのユーザープロファイルが使えなかった。

seleniumのインストール

$ pip3 install selenium

Firefox ESRのインストール

Raspberry Pi OSで動作するものはiceweaselとFirefox ESRがあるが、iceweaselは動作が不安定だったので急遽、Firefox ESRを採用。

$ sudo apt install firefox-esr

geckodriverのインストール

# ARM7のバイナリをダウンロード
$ wget https://github.com/mozilla/geckodriver/releases/download/v0.23.0/geckodriver-v0.23.0-arm7hf.tar.gz
$ tar -zxvf geckodriver-v0.23.0-arm7hf.tar.gz
$ sudo mv geckodriver /usr/local/bin

GitHub: mozilla / geckodriver v0.23.0

ユーザープロファイルを使う

  • firefox-esrを使うのでディスプレイのあるパソコンでFirefox ESRをインストールする。
    https://www.mozilla.org/en-US/firefox/78.3.0/releasenotes/

  • Firefox ESRでGoogleにログインしたりTwitterにログインしたりいろいろやった後...

  • セッション情報はFirefox ESRのプロファイルのcookies.sqliteとplaces.sqliteにあるのでとってくる。
    プロファイルの場所
    C:\Users\user\AppData\Roaming\Mozilla\Firefox\ ********.default-esr
    ScreenShot_20200927182722.png

  • 取ってきたファイルをRaspberry Piに転送してcookies.sqliteとplaces.sqliteを分かりやすくフォルダにまとめる。(フォルダ名は任意)

pi@raspberrypi:~ $ cd myProfile
pi@raspberrypi:~/myProfile $ ls
cookies.sqlite  places.sqlite

動作確認

from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep

Options = webdriver.FirefoxOptions()
# ヘッドレス
Options.headless = True
# 必須
Options.add_argument('--no-sandbox')
Options.add_argument('--disable-gpu')
# エラーの許容
Options.add_argument('--ignore-certificate-errors')
Options.add_argument('--allow-running-insecure-content')
Options.add_argument('--disable-web-security')
# headlessでは不要そうな機能
Options.add_argument('--disable-desktop-notifications')
Options.add_argument("--disable-extensions")
# UA設定(なくてもいい)
Options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0')
# 言語
Options.add_argument('--lang=ja')
# ユーザープロファイル
Options.profile = "myProfile"

driver = webdriver.Firefox(options=Options)
driver.get("http://www.example.com/")
print(str(driver.page_source))
print("successfully!")

エラーが出た場合はgeckodriver.logに詳細が記録される。

結論

もっと簡単なやり方があると思うのだが、個人的には意外に大掛かりだった。
軽いサイトならヘッドレスでスクレイピングすることが出来たが、10MB以上あるサイトはRaspberry Piでは重すぎて処理の途中でタイムアウトになってしまった・・・
Raspberry Piでのスクレイピングは安定性がないので遊びで使う程度なら十分だ。

リファレンス

2
5
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
2
5