LoginSignup
15
18

More than 5 years have passed since last update.

pythonでログイン認証ありサイトからスクレイピング

Last updated at Posted at 2019-01-14

目的

毎回ログイン認証するのが面倒なので。

参考サイト

こちらを参考にしました。
Python + Selenium で Chrome の自動操作を一通り

環境

Windows10 home 64bit
python3.6.5

準備

pip install selenium
pip install chromedriver-binary 

ChromeDriver を Python でのみ利用するため実行ファイルはダウンロードせず、コード内でchromedriver-binaryをimportします。

実行

コードはこちら
gist

はじめに、安全のためログインID・パスワードを環境変数へ書き出し、実行のたびに環境変数から読み込むようにします。

#書き込み
import os
os.environ["MY_LOGIN_ID"] = "YOUR_LOGIN_ID"
os.environ["MY_LOGIN_PASSWORD"] = "YOUR_LOGIN_PASSWORD"

メインクラスを作成します。

ScrapeLoginAuthSite.py
import chromedriver_binary
from selenium import webdriver

class ScrapeLoginAuthSite():
    def __init__(self,username,password):
        self.username = username
        self.password = password
        self.url = "WEBSITE_URL"
        #chrome driver -headless mode
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        self.driver = webdriver.Chrome(options=options)
        #if you want debug 
        #self.driver = webdriver.Chrome()

実際はheadlessモードで実行しますが、ブラウザを表示し画面の挙動を確認しながら実行するにはoptionsを無効にします。

認証を行うメイン関数を実装します。実際のログイン画面を見ながら取得する要素を決定します。こちらのサイトが参考になりました。Selenium API(逆引き)
最後にsubmit_button.submit()で認証ボタンを押します。

ScrapeLoginAuthSite.py
    def main(self):
        driver = self.driver
        #Login window
        print("login window open")
        driver.get(self.url)
        username_box = driver.find_element_by_id("userId")
        username_box.send_keys(self.username)
        password_box = driver.find_element_by_id("password")
        password_box.send_keys(self.password)
        submit_button = driver.find_element_by_id("loginButton")
        submit_button.submit()

ログインが成功したら、任意の要素を取得し、テキストを返します。

ScrapeLoginAuthSite.py
    # Mypage window
        if "https://MYPAGE_URL" in driver.current_url:
            print("Mypage window open")
            element = driver.find_element_by_id("element_id")
            return element.text 

最後にブラウザを閉じて終了します。

ScrapeLoginAuthSite.py
# destractor
    def __del__(self):
        print("del:driver")
        self.driver.quit()

実装が完了したら、以下のように実行します。

if __name__ == "__main__":
  login_id = os.environ.get("MY_LOGIN_ID")
  login_pass = os.environ.get("MY_LOGIN_PASSWORD")
  text = ScrapeLoginAuthSite(login_id,login_pass).main()

以上

15
18
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
15
18