Как достать имя и фамилию по id вк пользователя Python?
выдаёт ошибку:
line 3, in
session = vk.Session()
NameError: name ‘vk’ is not defined
как правильно сделать?
P.S. решил, проблема была в том что vk и vk_api разные библиотеки
- Вопрос задан более трёх лет назад
- 6013 просмотров
- Вконтакте
Реализация кода совершено неправильна, код, как и сказал юзер o5a относится к библиотеке vk.
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 )
Сбор данных с помощью API Вконтакте
Давайте поговорим о том, как используя API, вы можете получить и отсортировать данные всего несколькими командами. В продолжение темы сбора данных из социальной сети Вконтакте, хотим поделиться своим опытом по поиску пользователей и их друзей.
Так вот, сделав несколько пробных выборок для анализа, мы поняли, что поиск по фамилии и имени дает слишком ненадежные результаты, т.к. даты рождения многих пользователей скрыты, и даже выгрузив все совпадения по ФИ, вы все равно не сможете потом идентифицировать нужные данные.
Важно: мы заметили, что при поиске по ФИ + ДР Вконтакте выдаст подходящих пользователей, даже если их дата рождения скрыта. Это можно было использовать, только нужно обеспечить связь с данными поискового запроса. Для работы с API VK мы решили использовать Python с библиотекой vk_api (установка: pip install vk_api). Итого нам потребуются 2 библиотеки:
Далее – импорт входных данных в формате ID, Имя, Фамилия, Отчество (можно оставить пустым, так как Вконтакте отчество отсутствует), День рождения, Месяц рождения, Год рождения. Пример: (0,Пет, Петрови, ,1,1,1950)
Name already in use
vk-python-client / users.py /
- Go to file T
- Go to line L
- Go to definition R
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters