[Python] How to login into Instagram using Python Requests?

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am using the following code to make a Python Request to login into my Instagram account. I am running this on local.

    import requests
    from datetime import datetime
    import re
    from pprint import pprint
    import json


    time = int(datetime.now().timestamp())
    link = 'https://www.instagram.com/accounts/login/'
    login_url = f"https://www.instagram.com/accounts/login/ajax/"

    payload = {
    'username': 'username',
    'enc_password': 'PWD_INSTAGRAM_BROWSER:0:{time}:password',
    'queryParams': "{}",
    'optIntoOneTap': 'false',
    'stopDeletionNonce': "",
    'trustedDeviceRecords': "{}"
    }


    response = requests.get(link)
    csrf = response.cookies['csrftoken']
    print(csrf)

    response = requests.post(login_url, data=payload, headers={
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
    "X-Xequested-Xith": "XMLHttpRequest",
    "Referer": "https://www.instagram.com/",
    "X-CSRFtoken": csrf,
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "www.instagram.com",
    "Origin": "https://www.instagram.com"
    })

    response_json = json.loads(response.text)
    pprint(response_json)


    The response I receive after running the above code shows that I request is not authenticated:

    {'authenticated': False, 'status': 'ok', 'user': True}

    How can I login to Instagram using requests? Is there an updated method?

    Continue reading...

Compartilhe esta Página