I
I
Ivan Tuzhilkin2016-08-23 00:13:45
Python
Ivan Tuzhilkin, 2016-08-23 00:13:45

How to use the requests library or any other library to log in to the github.com site?

This option does not pass authorization.

#!/usr/bin/env python3
import requests

login = 'fake_password'
password = 'fake_login'
url_login = 'https://github.com/login'
url = 'https://github.com/'

with requests.Session() as s:
    s.auth = (login, password)
    r = s.get(url_login)
    print(r.url)
    print(r.status_code)
    r2 = s.get(url)
    print(r2.url)
    #Сохраняем страницу для проверки содержимого
    with open('git.html', 'w', encoding='utf-8') as page:
        page.write(r2.text)

Selenium Webdriver прошу не предлагать. Мои попытки отправлять форму data = playload, а также headers к успеху не привели. Авторизация на Github мне нужна для примера реализации, поэтому если кто-то из Вас делал авторизацию с помощью requests или любой другой библиотеки на любом сайте, где есть передача формы защищенной токеном и сохранение сессии между запросами, то такой код будет крайне полезен.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2016-08-23
@Ivan_Tuzhilkin

import requests
from bs4 import BeautifulSoup


LOGIN = ''
PASSWORD = ''

login_page = 'https://github.com/login'
auth_page = 'https://github.com/session'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
payload = {'login': LOGIN,
          'password': PASSWORD,
          'authenticity_token': '',
          'commit': 'Sign in',
          'utf8': '✓'}

with requests.Session() as session:
    s = session.get(login_page, headers=headers)
    soup = BeautifulSoup(s.text, 'html.parser')

    auth_token = soup.find('input', attrs={'name': 'authenticity_token'})
    payload['authenticity_token'] = auth_token['value']

    s = session.post(auth_page, data=payload, headers=headers)

    print(s.text)

You were rightly told, use the API. There is even an example on the main page for requests .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question