📜 ⬆️ ⬇️

We select valid mobile numbers of VK friends in Python



In the process of learning Python, it became interesting to try it in conjunction with the VK API. In VK there is a phone book, it shows the phones of your friends in a more or less convenient format. Since not always people willingly leave hollow (valid) numbers of their phones there, the idea to write a script that would select only valid mobile phone numbers and give them out as a separate table seemed interesting to me. Our phone book will generate a csv-file, which can then be opened, for example, in excel.

To use the VK API in Python, I googled the excellent, in my opinion, library with the original name vk.
So, we import the necessary modules:

import vk from time import sleep from re import sub, findall from getpass import getpass from csv import writer, QUOTE_ALL 

Create a User class with the necessary methods:
')
 class User(object): """VK User""" def __init__(self, login, password): self.login = login self.password = password self.id = '' #   def auth(self): session = vk.AuthSession(app_id='5340228', user_login=self.login, user_password=self.password) api = vk.API(session) return api #     def friends(self, api): #    ,       user_friends = api.friends.get(user_id=self.id, order='hints') return user_friends #    def friends_count(self, api): user_friends = User.friends(self, api) friends_count = len(user_friends) return friends_count #      def info(self, api): user = api.users.get(user_id=self.id) return user[0] 

I could not solve the problem for a long time, and in Google somehow I didn’t come across how to get the id of the current user. By a lucky chance I found a way out - I need to pass an empty string as an argument.

Next, we write the function validator, which will bring the mobile numbers to a common form. I, as a resident of Ukraine, are interested in choosing only Ukrainian mobile numbers that should start at “0”. The script is easy to fix for any format.

 def norm_mob(str): if len(str) != '': norm_mob = sub(r'(\s+)?[+]?[-]?', '', str) #          right_mob = findall(r'[\d]', norm_mob) #       ,     if (len(right_mob) == len(norm_mob)) and (len(norm_mob) >= 10): rev_norm_mob = norm_mob[::-1] norm_mob = rev_norm_mob[0:10] if norm_mob[::-1][0] == '0': return norm_mob[::-1] else: return False 

Next, we go through friends, select those who left their contacts, and if they did, then we validate them and write them into an array. The VC server does not like a large number of requests, so we make our script sleep for some time between them, try different values, these turned out to be optimal.

 def find_correct_phone_numbers(api, friends, friends_count): users_phones = [] for i in range(0, friends_count): cur_user_id = int(friends[i]) cur_user = api.users.get(user_id=cur_user_id, fields='contacts') try: #     cur_mob = cur_user[0]['mobile_phone'] except KeyError: sleep(0.3) continue mob = norm_mob(cur_mob) if mob: #        users_phones.append({ 'user_name': '{} {}'.format(cur_user[0]['first_name'], cur_user[0]['last_name']), 'user_phone': '8{}'.format(mob) }) sleep(0.4) return users_phones 

Save the result.

 def saveCSV(data, path): with open(path, 'w') as csvfile: my_writer = writer(csvfile, delimiter=' ', quotechar='"', quoting=QUOTE_ALL) my_writer.writerow((' ', ' . ')) for item in data: try: my_writer.writerow((item['user_name'], item['user_phone'])) except Exception: my_writer.writerow(('(  )', item['user_phone'])) 

Add a function that would count the elapsed time.

 class Timer(object): def __enter__(self): self._startTime = time() def __exit__(self, type, value, traceback): howLong = time() - self._startTime print(" : {:.2f} ".format(howLong/60)) 

Well and the final stage, we will make a call of the written functions.

 def main(): while True: login = input('E-mail: ') password = getpass('Password: ') try: vk_user = User(login, password) api = vk_user.auth() print('  !') break except Exception: print('   , ,  .') friends = vk_user.friends(api) friends_count = vk_user.friends_count(api) print(' {} .'.format(friends_count)) print('   ...') with Timer() as p: users_phones = find_correct_phone_numbers(api, friends, friends_count) print(' . ...') saveCSV(users_phones, 'vk_mob.csv') print('  .') if __name__ == '__main__': main() 

At the output we get a csv-file that can be opened in excel in the format of a convenient table.

Source: https://habr.com/ru/post/279803/


All Articles