Help us understand the problem. What is going on with this article?

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

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)
sssssssiiiiinnn
24歳です。 某SIerで働いてます。 Deep Learningの勉強中。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした