Usage
Several types of APIs are implemented in this module. Each of them is needed for certain purposes, but they are all united by the way of accessing the VK API. After initializing the class, you can call any method. Let’s try to figure out what’s going on here:
It gets user info with user id equal to 1. vk.api.APINamespace object is used to create API request and send it via original vk.session.API class object (or another), which in turn, manages access token, sends API request, gets JSON response, parses and returns it.
vk.API
The simplest VK API implementation. Can process any API method that can be called from the server
access_token (Optional[str]) – Access token for API requests obtained by any means (see documentation ). Optional when using InteractiveMixin
**kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
vk.UserAPI
Subclass of vk.session.API . It differs only in that it can get access token using user credentials (Implicit flow authorization).
This implementation uses the web version of VK to log in and receive cookies, and then obtains an access token through Implicit flow authorization. In the future, VK may change the approach to authorization (for example, replace it with VK ID) and maintaining operability will become quite a difficult task, and most likely it will be deprecated. Use vk.session.DirectUserAPI instead
user_login (Optional[str]) – User login, optional when using InteractiveMixin
user_password (Optional[str]) – User password, optional when using InteractiveMixin
client_id (Optional[int]) – ID of the application to authorize with, defaults to “VK Admin” app ID
scope (Optional[Union[str, int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to ‘offline’
**kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
Callback to retrieve authentication check code (if account supports 2FA). Default behavior is to raise exception, redefine in a subclass
The authentication check code can be obtained in the sent SMS, using Google Authenticator (or another authenticator), or it can be one of ten backup codes
vk.DirectUserAPI
Subclass of vk.session.UserAPI . Can get access token using user credentials (through Direct authorization).
Necessary data (client_id and client_secret) from other official applications
user_login (Optional[str]) – User login, optional when using InteractiveMixin
user_password (Optional[str]) – User password, optional when using InteractiveMixin
client_id (Optional[int]) – ID of the official application, defaults to “VK for Android” app ID
client_secret (Optional[str]) – Client secret of the official application, defaults to client secret of “VK for Android” app
scope (Optional[Union[str, int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to ‘offline’
**kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
vk.CommunityAPI
Subclass of vk.session.UserAPI . Can get community access token using user credentials (Implicit flow authorization for communities). To select a community on behalf of which to make request to the API method, you can pass the group_id param (defaults to the first community from the passed list)
This implementation uses the web version of VK to log in and receive cookies, and then obtains an access tokens through Implicit flow authorization for communities. In the future, VK may change the approach to authorization (for example, replace it with VK ID) and maintaining operability will become quite a difficult task, and most likely it will be deprecated.
You can create a group token on the management page: Community -> Management -> Working with API -> Access Tokens -> Create a token (bonus — the token has no expiration date)
user_login (Optional[str]) – User login, optional when using InteractiveMixin
user_password (Optional[str]) – User password, optional when using InteractiveMixin
group_ids (List[int]) – List of community IDs to be authorized
client_id (Optional[int]) – ID of the application to authorize with, defaults to “VK Admin” app ID
scope (Optional[Union[str, int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to None . Be careful, only manage, messages, photos, docs, wall and stories are available for communities
**kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
Авторизация в VK с помощью requests
Хочу авторизоваться на сайте vk.com и получить html своей страницы. В запросе передаю логин/пароль как параметры формы.
На что получаю html с предложение пройти авторизацию. Что я делаю не так?
Я не знаю, на основании чего вы такой код написали.
Но для авторизации в VK использует oauth, читаем доки.
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
VK requests for humans™
vk.com is the largest social network in Russia.
Requirements
- python (2.7, 3.4, 3.5, 3.6)
NOTE: Python 2.7 will be no longer supported starting from the version 2.0.0
Install
Usage and features
Simple queries
User token with login and password
Fits the usecase when you run queries from one on the backend from one of your accounts
Using service token
Service token is preferable way, because it does not require user credentials and oauth requests, but not all the methods can be called with service token (e.g execute can’t be)
More info about service token.
Using client access token
For example when you got a token on the client side (implicit flow) and want to query API on the backend.
Use service_token parameter as in the example above.
User token with client_secret (Direct Authorization)
Trusted applications can get unlimited access_token to access API by passing with application ID, username, password and client_secret — secret key of your application.
More info about Direct Authorization.
Using custom parameters
Scope or api version
Just pass scope and/or api_version parameters like
HTTP parameters
To override requests http parameters (e.g ssl options), just use http_params as follows:
Using HTTP proxy
To use proxy server just pass it to the http_params , e.g
For more info, take a look at requests docs
Enable logging
To enable library logging in your project you should do as follows:
Auto-resolving conflicts when you’re getting access from unusual place
Just pass your phone number during API initialization. In case of security check it will be handled automatically, otherwise console input will be asked
Interactive session
Interactive session gives you control over login parameters during the runtime.
Useful if
- 2FA authentication required
- CAPTCHA required
- For testing purposes
Usage
If you don’t pass login, password and app_id you will be asked to prompt it, i.e having this
You will be asked only for 2FA authentication or captcha code if required
Streaming API
Streaming API allows to subscribe on the events from vk.
NOTE: Only for python 3.4 and later
Install
Stream rules
Consumer
Streaming API provides convenient coroutine-based handler interface (callback)
Official API docs
Tests
Tests are mostly checking integration part, so it requires some vk authentication data.
Before running tests locally define environment variables:
Bug tracker
Warm welcome for suggestions and concerns. Feel free to submit it to the Issues section
Авторизация в VK для людей
Здравствуй, дорогой читатель. Если тебе хотя бы однажды доводилось работать с API Вконтакте и при этом писать все на python , вероятно, авторизация приложения заставила тебя сделать несколько приседаний, после которых ног либо не чувствуешь и падаешь в обморок, либо вкачиваешь квадрицепс и все же пробиваешь API, как Ван Дамм.
По какой-то причине этот, казалось бы, самый непримечательный этап поначалу отнимает огромное количество сил и времени. Моя задача: помочь читателям Хабра избежать травм ног.
Далее я предлагаю рассмотреть небольшую библиотеку, позволяющую в одну строчку авторизовать свое приложение для конкретного пользователя и получить access_token . В конце статьи представлена ссылка на github-репозиторий этой библиотеки с quickstart’ом в README -файле.
Задача
Хотим небольшой модуль, который позволяет провести авторизацию красиво, универсально и максимально надежно, а использовать который очень просто.
Стоит сказать, что данное решение является усовершенствованием и обобщением варианта, предложенного в этой статье.
Итак, используем python3.5 , библиотеку для html запросов requests и getpass для скрытого ввода пароля.
Наша задача: несколько раз обратиться по верному адресу, каждый раз парсить <form> , отправлять ответ и наконец получить желанный access_token .
Реализация
Начнем с создания класса. При инициализации будем требовать список «разрешений», к которым приложение хочет получить доступ, id этого приложения и версию API VK. Плюсом добавим несколько необязательных параметров, значение каждого из которых прояснится далее.
Как было сказано в уже упомянутой статье, нам необходимо искусно ворочать cookie и redirect’ы. Все это за нас делает библиотека requests с объектом класса Session. Заведем и себе такой в поле self.session . Для парсинга html документа используется стандартный класс HTMLParser из модуля html.parser . Для парсера тоже написан класс ( FormParser ), разбирать который большого смысла нет, так как он почти полностью повторяет таковой из упомянутой статьи. Существенное отличие лишь в том, что использованный здесь позволяет изящно отклонить авторизацию приложения на последнем шаге, если вы вдруг передумали.
Поля user_id и access_token будут заполнены после успешной авторизации, response хранит в себе результат последнего html запроса.
Пользователю библиотеки предоставим один-единственный метод – authorize , который совершает 3 шага:
- запрос на авторизацию приложения
- авторизация пользователя
2.1 введение кода-ключа в случае двух-факторной авторизации - подтверждение разрешения на использование permissions
Пройдемся по каждому шагу.
Шаг 1. Запрос на авторизацию приложения
Аккуратно составляем url запроса (про параметры можно прочитать здесь), отправляем запрос и парсим полученный html.
Шаг 2. Авторизация пользователя
Реализованы методы _log_in() и _two_fact_auth() для [не]успешной авторизации пользователя в вк, если он не авторизован (а он точно не авторизован). Оба метода используют ранее определенные поля email , pswd , two_factor_auth и security_code . Если какое-то из полей не было подано аргументом при инициализации объекта класса VKAuth , их попросят ввести в консоли, а случае неудачи попросят ввести заново. Двух-факторная авторизация опциональна и по умолчанию отключена, и наш модуль уведомляет пользователя о ее присутствии ошибкой.
Шаг 3. Подтверждение permissions и получение access_token
Самое сложное позади. Теперь дело за малым. Используем наше усовершенствование парсера формы, чтоб найти в только что поступившем к нам html документе кнопку с надписью «Allow» и вытащить из нее url подтверждения авторизации. Рядом находится кнопка с отказом – сохраним и ее url. Поле auto_access по умолчанию находится в состоянии True , так что это подтверждение ни чуть не должно осложнить нам жизнь.
Наконец, сохраним полученные access_token и user_id из url, который был передан после подтверждения авторизации.