Python http get user password

Authentication¶

This document discusses using various kinds of authentication with Requests.

Many web services require authentication, and there are many different types. Below, we outline various forms of authentication available in Requests, from the simple to the complex.

Basic Authentication¶

Many web services that require authentication accept HTTP Basic Auth. This is the simplest kind, and Requests supports it straight out of the box.

Making requests with HTTP Basic Auth is very simple:

>>> from requests.auth import HTTPBasicAuth >>> basic = HTTPBasicAuth(‘user’, ‘pass’) >>> requests.get(‘https://httpbin.org/basic-auth/user/pass’, auth=basic)

In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand for using it:

>>> requests.get(‘https://httpbin.org/basic-auth/user/pass’, auth=(‘user’, ‘pass’))

Providing the credentials in a tuple like this is exactly the same as the HTTPBasicAuth example above.

netrc Authentication¶

If no authentication method is given with the auth argument, Requests will attempt to get the authentication credentials for the URL’s hostname from the user’s netrc file. The netrc file overrides raw HTTP authentication headers set with headers= .

If credentials for the hostname are found, the request is sent with HTTP Basic Auth.

Digest Authentication¶

Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:

>>> from requests.auth import HTTPDigestAuth >>> url = ‘https://httpbin.org/digest-auth/auth/user/pass’ >>> requests.get(url, auth=HTTPDigestAuth(‘user’, ‘pass’))

OAuth 1 Authentication¶

A common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:

>>> import requests >>> from requests_oauthlib import OAuth1 >>> url = ‘https://api.twitter.com/1.1/account/verify_credentials.json’ >>> auth = OAuth1(‘YOUR_APP_KEY’, ‘YOUR_APP_SECRET’, . ‘USER_OAUTH_TOKEN’, ‘USER_OAUTH_TOKEN_SECRET’) >>> requests.get(url, auth=auth)

For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub

OAuth 2 and OpenID Connect Authentication¶

The requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:

Other Authentication¶

Requests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:

If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions.

New Forms of Authentication¶

If you can’t find a good implementation of the form of authentication you want, you can implement it yourself. Requests makes it easy to add your own forms of authentication.

To do so, subclass AuthBase and implement the __call__() method:

>>> import requests >>> class MyAuth(requests.auth.AuthBase): . def __call__(self, r): . # Implement my authentication . return r . >>> url = ‘https://httpbin.org/get’ >>> requests.get(url, auth=MyAuth())

When an authentication handler is attached to a request, it is called during request setup. The __call__ method must therefore do whatever is required to make the authentication work. Some forms of authentication will additionally add hooks to provide further functionality.

Further examples can be found under the Requests organization and in the auth.py file.

Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.

Table of Contents

Источник

Python requests. Авторизация на сайте

Иногда при парсинге страниц нужно получить данные , которые недоступны незарегистрированным пользователям. Для этого нужно авторизоваться на сайте. И в этой статье я покажу как с помощью замечательной библиотеки requests это реализовать.

В качестве примера попробуем залогиниться на сайте hh.ru.

Python авторизация

Как видим нам нужно ввести Email или Телефонный номер в качестве ЛОГИНА и ПАРОЛЬ и нажать кнопку Войти в личный кабинет.

Установка библиотеки Requests

Указываем User-Agent

Казалось бы , нам нужно просто реализовать метод post этой библиотеки , передав все необходимые данные. Но не так просто , так как нам нужно указать правильный User-Agent и вытащить из кукис файлов значение _xsrf.

User-agent ? И что за значение _xsrf ? Что ты несешь , чувак? Наверно, такие вопросы у вас возникли читая предыдущие строки.Попробую объяснить о чем речь

Попытаемся просто сделать GET запрос на сайт hh.ru и посмотреть какой ответ он возвращает.

Python авторизация

Как мы видим сервер нам возвращает ОТВЕТ 404 , который говорит , что нет такой страницы. Но если мы выполним запрос через браузер , то все нормально.

Такая ошибка происходит из-за того , что сервер думает , что мы робот , так по умолчанию User-Agent отправляемого запроса равен python-requests/2.22.0. Чтобы сервер нам возвращал нормальный ответ , нужно указать правильный User-Agent, который эмулирует действия пользователя.

 import requests headers = < 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' >r = requests.get("https://hh.ru", headers=headers) print(r) 

Объект Session

Теперь разберемся для чего нужен _xsrf . Когда мы логинимся на сайте hh.ru , то мы просто вводим логин и пароль и все. Но при этом при POST запросе на сервер кроме введенных нами значений передается и параметр _xsrf, который нужен для защиты от CSRF-атак. Так вот значение этого параметра сервер hh.ru генерирует автоматически и хранит его в кукис файлах в браузере и чтобы получить это значение , нам нужно использовать объект Session библиотеки requests.

Объект Session позволяет сохранять определенные параметры в запросах.Он также сохраняет файлы COOKIE во всех запросах.

Здесь я привожу полный текст скрипта с подробными комментариями, который осуществляет авторизаицю на сайте hh.ru.

 import requests url = 'https://moscow.hh.ru/account/login' # Важно. По умолчанию requests отправляет вот такой # заголовок 'User-Agent': 'python-requests/2.22.0 , а это приводит к тому , что Nginx # отправляет 404 ответ. Поэтому нам нужно сообщить серверу, что запрос идет от браузера user_agent_val = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' # Создаем сессию и указываем ему наш user-agent session = requests.Session() r = session.get(url, headers = < 'User-Agent': user_agent_val >) # Указываем referer. Иногда , если не указать , то приводит к ошибкам. session.headers.update() #Хотя , мы ранее указывали наш user-agent и запрос удачно прошел и вернул # нам нужный ответ, но user-agent изменился на тот , который был # по умолчанию. И поэтому мы обновляем его. session.headers.update() # Получаем значение _xsrf из cookies _xsrf = session.cookies.get('_xsrf', domain=".hh.ru") # Осуществляем вход с помощью метода POST с указанием необходимых данных post_request = session.post(url, < 'backUrl': 'https://moscow.hh.ru/', 'username': 'yourlogin', 'password': 'yourpassword', '_xsrf':_xsrf, 'remember':'yes', >) #Вход успешно воспроизведен и мы сохраняем страницу в html файл with open("hh_success.html","w",encoding="utf-8") as f: f.write(post_request.text) 

Заключение

В этой статье реализована практическая задача , которая осуществляет авторизацию на сайте hh.ru. Эта задача прекрасна иллюстрирует то , с чем мы можем столкнуться на практике

Обновлено(1 декабря 2020 года)

Когда писалась данная статья , то капчи(CAPTCHA) не было на сайте hh.ru и авторизация происходила успешно. Для обхода капчи нужны более сложные решения. А для авторизации на страницах , где нет капчи можно использовать вышеописанный метод. Также у меня есть статья , где рассмотрена авторизация на сайте вконтакте с помощью логина и пароля , c использованием библиотеки vk_api

Источник

Authentication using Python requests

Authentication refers to giving a user permissions to access a particular resource. Since, everyone can’t be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server.

Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.

If you an invalid username or password, it will return an error as –

Types of Authentication

Digest Authentication
Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:

>>> from requests.auth import HTTPDigestAuth >>> url = ‘https://httpbin.org/digest-auth/auth/user/pass’ >>> requests.get(url, auth=HTTPDigestAuth(‘user’, ‘pass’))

OAuth 1 Authentication
A common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:

>>> import requests >>> from requests_oauthlib import OAuth1 >>> url = ‘https://api.twitter.com/1.1/account/verify_credentials.json’ >>> auth = OAuth1(‘YOUR_APP_KEY’, ‘YOUR_APP_SECRET’, . ‘USER_OAUTH_TOKEN’, ‘USER_OAUTH_TOKEN_SECRET’) >>> requests.get(url, auth=auth)

For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub

OAuth 2 and OpenID Connect Authentication
The requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:

Other Authentication
Requests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:

If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions.

Источник

Читайте также:  Html minimum maximum width
Оцените статью