LoginSignup
89
91

More than 5 years have passed since last update.

Python + Selenium + Chrome で自動ログインいくつか

Last updated at Posted at 2018-10-19

はじめに

ログインまわりを調べてみました。新しい情報ではないですが備忘録として。

基本的操作: Python + Selenium で Chrome の自動操作を一通り

Selenium のインストールや from selenium import webdriver がされているとします。
詳しくは上記の記事をご覧ください。

注意事項

どこかのサービスにログインした場合、もろもろの利用規約などに同意していると思います。
ならば、そもそも自動操作で処理して良いかなど、よく確認が必要です。
禁止されている事項がいろいろありえます。

スクリプトに書いておく

スクリプトに書いておく方法が最も単純です。
もちろん、プレーンテキストなので望ましくないことも多いです。

user_email = '...'
user_pw = '...'
driver.find_element_by_id("email").send_keys(user_email)
driver.find_element_by_id("password").send_keys(user_pw)
driver.find_element_by_class_name("login-button").click()

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

新規に作成してそこにログイン情報を保存していく方法と、既存の(Selenium 経由ではなく通常起動の Chrome での)ユーザプロファイルを読み込む方法があります。
普段使いの Chrome のプロファイルと混ぜたくないならば前者、もろもろの既存の情報を引き継いで処理を進めたいなら後者でしょうか。

なお、ヘッドレスモードではうまくうごかせていません。

新規に作成する

  1. ChromeOptions を利用します。適当な空のフォルダ作成しておき、add_argument('--user-data-dir=...') で指定します(絶対パス、相対パスどちらでも可)。
  2. 非ヘッドレスモードで Chrome を起動し、ログイン情報を残したい適当なページに行き、ログイン、パスワード、二段階認証等が終われば閉じます。(スクリプトから立ち上げるときは driver.quit() まで呼ばないよう注意)
  3. 次回、同じプロファイルフォルダを指定すれば、ログインした状態になります。
import os
userdata_dir = 'UserData'  # カレントディレクトリの直下に作る場合
os.makedirs(userdata_dir, exist_ok=True)

options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=' + userdata_dir)

driver = webdriver.Chrome(options=options)

新規作成したユーザディレクトリを、さらにマルチユーザーで使用するなら --profile-directory= も指定が必要ですが、通常は不要です。

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

  1. 使用したい Chrome ユーザーで Selenium を使わずに Chrome を通常起動します。
  2. URLの欄に chrome://version/ と入力し、「プロフィール パス」を調べます。
    • Windows であれば C:\Users\<ユーザ名>\AppData\Local\Google\Chrome\User Data\Profile 2 などになります。
    • User Data の部分までがユーザデータディレクトリのパス、最後の Profile 2プロファイルディレクトリ名です。
    • デフォルトユーザーだとプロファイルディレクトリが Default になっています。
  3. スクリプト内で、--user-data-dir にユーザデータディレクトリのパス、--profile-directory にプロファイルディレクトリ名を指定し、Selenium から Chrome を起動すると、既存ユーザの設定が読み込まれます。
    • Default ユーザーのプロファイルを読み込む場合は、--profile-directory は不要です。
options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=C:\\Users\\<ユーザ名>\\AppData\\Local\\Google\\Chrome\\User Data')
options.add_argument('--profile-directory=Profile 2')  # この行を省略するとDefaultフォルダが指定されます

driver = webdriver.Chrome(options=options)

参考: http://katsulog.tech/create-an-arbitrary-chrome-profile-with-selenium-webdriver-and-store-login-information-etc/

その他のパスワード入力方法

getpass でその場で聞く、暗号化ライブラリを使う、keyring を使ってOSのパスワード保存機構に任せる、などがあるようです。

参考: https://www.tsuyukimakoto.com/blog/2013/12/02/hide_password/

89
91
4

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
89
91