Stack Overflow на русском Asked by BrainSwitch on December 10, 2020
Как получить и сохранить(для дальнейшего использования) cookie при использовании instagram private api? Искал долго и ничего не нашел.
from instagram_private_api import Client
user_name = 'YOUR_LOGIN_USER_NAME'
password = 'YOUR_PASSWORD'
api = Client(user_name, password)
# получаем объект
cookie_jar = api.cookie_jar
# далее извлечь куки, куда-то записать
А потом как их применить не понятно
from instagram_private_api import Client
user_name = 'YOUR_LOGIN_USER_NAME'
password = 'YOUR_PASSWORD'
api = Client(user_name, password, cookie = ?)
В документации написано: "cookie: Saved cookie string from a previous session"
Но там несколько строк cookie.
я использовал код чужой и немного изменил его, специально для сохранения куки и все записывал в БД
def to_json(python_object):
if isinstance(python_object, bytes):
return {'__class__': 'bytes',
'__value__': codecs.encode(python_object, 'base64').decode()}
raise TypeError(repr(python_object) + ' is not JSON serializable')
def onlogin_callback(api, username):
cache_settings = api.settings
cookies.set(username, json.dumps(cache_settings, default=to_json))
print('[I] New auth cookie file was made: {0!s}'.format(username))
def login(username, password):
device_id = None
try:
username_cookie = cookies.get(username)
if not username_cookie:
# settings file does not exist
print('[W] Unable to find auth cookie file: {0!s} (creating a new one...)'.format(username))
api = Client(
username, password,
on_login=lambda x: onlogin_callback(x, username))
else:
cached_settings = json.loads(username_cookie)
device_id = cached_settings.get('device_id')
# reuse auth settings
api = Client(
username, password,
settings=json.dump(cached_settings, sys.stdout))
print('[I] Using cached login cookie for "' + api.authenticated_user_name + '".')
except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
print('[E] ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))
# Login expired
# Do relogin but use default ua, keys and such
if username and password:
api = Client(
username, password,
device_id=device_id,
on_login=lambda x: onlogin_callback(x, username_cookie))
except ClientLoginError as e:
print('[E] Could not login: {:s}.n[E] {:s}nn{:s}'.format(
json.loads(e.error_response).get("error_title", "Error title not available."),
json.loads(e.error_response).get("message", "Not available"), e.error_response))
print('-' * 70)
sys.exit(9)
except ClientError as e:
print('[E] Client Error: {:s}'.format(e.error_response))
print('-' * 70)
sys.exit(9)
except Exception as e:
if str(e).startswith("unsupported pickle protocol"):
print("[W] This cookie file is not compatible with Python {}.".format(sys.version.split(' ')[0][0]))
print("[W] Please delete your cookie file 'credentials.json' and try again.")
else:
print('[E] Unexpected Exception: {0!s}'.format(e))
print('-' * 70)
sys.exit(99)
print('[I] Login to "' + api.authenticated_user_name + '" OK!')
cookie_expiry = api.cookie_jar.auth_expires
print('[I] Login cookie expiry date: {0!s}'.format(
datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %I:%M:%S %p')))
return api
где cookies -- База данных
Answered by Kamronbek on December 10, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP