LoginSignup
192
180

More than 5 years have passed since last update.

Pythonでのウェブサイトへのログイン

Posted at

流れ

  1. ログインしたいサービスのログインページに行き、ログインフォームのパラメータを調べる
  2. 必要な情報をログイン用のURLに送信し、セッションを開始する

以下では、Qiitaを例として話を進める。

パラメータの調べ方

Qiitaのログインフォームのソースは次のようになっている:

<form class="landingLoginForm" autocomplete="off" data-event_name="Login with password" action="/login" accept-charset="UTF-8" method="post">
  <input name="utf8" type="hidden" value="✓">
  <input type="hidden" name="authenticity_token" value="rYIMTVoDlb4eCzh6wZIRgiPQHmrr5ts9DyykDCE9FkHM7zQxX7WAhmUhW8y0BPIA3MvzH31KCFEyiPTVk4GBzQ==">
  <input type="text" name="identity" id="identity" placeholder="Username or email" autofocus="autofocus" class="form-control landingLoginForm_identity">
  <div class="row">
    <div class="col-sm-9 landingLoginForm_passwordColumn">
      <input type="password" name="password" id="password" placeholder="Password" class="form-control">
    </div>
    <div class="col-sm-3 landingLoginForm_submitColumn">
      <input type="submit" name="commit" value="Login" class="btn btn-primary btn-block" data-disable-with="Login">
    </div>
  </div>
  <div class="landingLoginForm_forgotPassword">
    <a href="https://qiita.com/sessions/forgot_password">Forgot Password?</a>
  </div>
  <div class="help-block js-email-invalid-message" style="display: none"></div>
</form>

これより、ログインボタンを押すとqiita.com/login

  1. utf8
  2. authenticity_token
  3. identity
  4. password

というデータが送信されることがわかる。このうち、utf8は規定値が与えられているのでそれを利用し、authenticity_tokenはアクセスごとに値が与えられるのでそれを取得する必要がある。残りのidentitypasswordには手打ちで情報を入力する。

サイトとの通信

PythonにはrequestsというHTTP通信のための便利なライブラリがあるので、それを使うのが無難。ログイン後はsessionのための値を保存する必要があるので、Sessionオブジェクトを経由して通信する。

また、上述のようにログイン前にauthenticity_tokenを取得しておく必要があるので、最初にトップページにアクセスしBeautifulSoupで値を取得する。

Qiitaにログインするサンプルスクリプトを以下に示す:

from bs4 import BeautifulSoup
import requests

payload = {
    'utf8': '✓',
    'identity': 'username or email',
    'password': 'secret'
}

# authenticity_tokenの取得
s = requests.Session()
r = s.get('https://qiita.com')
soup = BeautifulSoup(r.text)
auth_token = soup.find(attrs={'name': 'authenticity_token'}).get('value')
payload['authenticity_token'] = auth_token

# ログイン
s.post('https://qiita.com/login', data=payload)

# 以下でログイン後に可能となる処理をおこなう
...

注意

以上のような素朴な方法が上手くいかない場合もあるので(例えば、Googleへとログインするには2段階の認証作業が必要)、その都度HTTPのヘッダー情報などを細かくチェックしていく必要がある。

192
180
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
192
180