PythonとSelenimumで検索結果のスクリーンショットを撮る

準備

Pythonに関しては3.7.9がインストールされているという前提です。Pyenvでバージョンを切り替えることをお勧めします。まずはPythonでSeleniumを扱えるように下記のコマンドを実行して下さい。

$ pip install selenium
$ pip install chromedriver

またターミナルにChromeDriverをインストールしていない場合は下記のコマンドでインストールして下さい。

$ brew install chromedriver

スクリプト作成

こちらを参考にします。まずimageディレクトリを作成します。

$ mkdir image

続いて下記のPythonファイルを作成します。chromedriverのパスが環境によって異なるかと思うので、find / -name "chromedriver"の結果を11行目に記述して下さい。

12行目のURLもロサンゼルスの天気をGoogle検索した時のURLを指定しています。

import os
import sys
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# File Name
FILENAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "image/screen.png")

# set driver and url
driver = webdriver.Chrome('/usr/local/bin/chromedriver')
url = 'https://www.google.com/search?q=ロサンゼルス 天気'
driver.get(url)

# get width and height of the page
w = driver.execute_script("return document.body.scrollWidth;")
h = driver.execute_script("return document.body.scrollHeight;")

# set window size
driver.set_window_size(w,h)

# Get Screen Shot
driver.save_screenshot(FILENAME)

# Close Web Browser
driver.quit()

下記のコマンドを実行してimageディレクトリに下図の画像が保存されていれば成功です。

$ python3 image.py

保存した画像を使う

スクショした画像はSlackに投稿すると便利です。

$ curl -XPOST -F "file=@【画像のパス】" -F channels="【SlackのチャンネルID】" -H "Authorization: Bearer 【Slackの認証トークン】" https://slack.com/api/files.upload

こんな感じでbotみたいに定期的に天気を教えてくれると色々と楽です。

以上です。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA