LoginSignup
1
3

ラズパイで簡単にSeleniumをはじめる

Posted at

ラズパイでスクレイピングしたい

リアルタイムで監視するのにPaaSだと柔軟性がない(お金がかかる)ので諦めて一から何でもできる環境を作ることにしました

環境構築

  • sample-envには好きな環境名を付けます。
python -m venv sample-env
  • 環境内に入る
source sample-env/bin/activate
  • Seleniumをインストールする
pip install selenium
  • chromium driverをインストール
sudo apt install -y chromium-browser

実行

  • 以下Pythonコードを記述し、実行
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

options = Options()
options.BinaryLocation = ("/usr/bin/chromium-browser")
options.add_argument('--no-sandbox')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')

service = Service("/usr/bin/chromedriver") # 
driver = webdriver.Chrome(options=options, service=service)
driver.get("最初に確認したいURL")
driver.save_screenshot("キャプチャ名")
driver.close()

上記のコードを修正して色々試してみてください。

余談

  • 以下のように記述すれば一致するクラス名のテキスト要素を取得できます。
# 単一クラスの場合
class_names="class-a"
# 複数クラスの場合
class_names=".class-a.class-b"

elements = driver.find_elements(By.CSS_SELECTOR, class_names)

for element in elements:
    text = element.text
    print(text)
1
3
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
1
3