LoginSignup
2
3

More than 3 years have passed since last update.

Pythonでqiitaにログインしてみる

Last updated at Posted at 2020-01-09

webスクレイピング入門としてqiitaへログインしてみました。
ログインボタンをクリックするとhttps://qiita.com/loginに対して以下のデータを送信しているようです。

  • utf-8:✓で固定
  • authenticity_token:セッションを張った際に発行されると思われる:
  • identity:メールアドレスかユーザID
  • password:パスワード

ということでコード内で取得する必要があるのはauthenticity_tokenだけですね。覚えたてのBeautifulSoupを使って取得してみました。

def get_authenticity_token(session, login_url):
    response = session.get(login_url)
    response.encoding = response.apparent_encoding
    bs = BeautifulSoup(response.text, 'html.parser')
    authenticity_token = str(bs.find(attrs={'name':'authenticity_token'}).get('value'))
    return authenticity_token

実際にログインまで行うと以下のようになります。

import requests
import os
from bs4 import BeautifulSoup


user_name = 'user_name'
user_password = 'user_password'
login_url = 'https://qiita.com/login'


login_form = {
    'utf-8':'✓',
    'authenticity_token':'token',
    'identity':user_name,
    'password':user_password
}


def get_authenticity_token(session, login_url):
    response = session.get(login_url)
    response.encoding = response.apparent_encoding
    bs = BeautifulSoup(response.text, 'html.parser')
    authenticity_token = str(bs.find(attrs={'name':'authenticity_token'}).get('value'))
    return authenticity_token


if __name__ == '__main__':
    session = requests.Session()
    authenticity_token = get_authenticity_token(session, login_url)
    login_form['authenticity_token'] = authenticity_token
    session.post(login_url, login_form)
2
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
2
3