Python Instagram login using requests

◇◆丶佛笑我妖孽 提交于 2021-02-08 06:15:06

问题


I am trying to login to Instagram with python. I am able to get the csrf Token but the requests.Session().post() doesn't seem to post the login data to the website correctly. I always get the class="no-js not-logged-in client-root". I've been searching for a while and also tried to login into some random sites which seemed to work. In the login method I just start a requests.Session() and make a post request to the https://www.instagram.com/accounts/login/ with the login name and password as the data parameter.

def login(self):
    with requests.Session() as s:
        p = s.post(self.loginUrl, data=self.loginData, allow_redirects=True)

Also please don't tell me to use Selenium I strictly want to do it with requests.


回答1:


Try using this code:

import requests

#Creating URL, usr/pass and user agent variables

BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
USERNAME = '****'
PASSWD = '*******'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\
 Chrome/59.0.3071.115 Safari/537.36'

#Setting some headers and refers
session = requests.Session()
session.headers = {'user-agent': USER_AGENT}
session.headers.update({'Referer': BASE_URL})


try:
    #Requesting the base url. Grabbing and inserting the csrftoken

    req = session.get(BASE_URL)
    session.headers.update({'X-CSRFToken': req.cookies['csrftoken']})
    login_data = {'username': USERNAME, 'password': PASSWD}

    #Finally login in
    login = session.post(LOGIN_URL, data=login_data, allow_redirects=True)
    session.headers.update({'X-CSRFToken': login.cookies['csrftoken']})

    cookies = login.cookies

    #Print the html results after I've logged in
    print(login.text)

#In case of refused connection
except requests.exceptions.ConnectionError:
    print("Connection refused")

I found it in this Youtube video. It worked for me, I hope it can work for you too.




回答2:


Currently (January 2021) a working solution to log into Instagram using Python is the following:

def login(username, password):
    """Login to Instagram"""

    time = str(int(datetime.datetime.now().timestamp()))
    enc_password = f"#PWD_INSTAGRAM_BROWSER:0:{time}:{password}"

    session = requests.Session()
    # set a cookie that signals Instagram the "Accept cookie" banner was closed
    session.cookies.set("ig_cb", "2")
    session.headers.update({'user-agent': self.user_agent})
    session.headers.update({'Referer': 'https://www.instagram.com'})
    res = session.get('https://www.instagram.com')

    csrftoken = None

    for key in res.cookies.keys():
        if key == 'csrftoken':
            csrftoken = session.cookies['csrftoken']

    session.headers.update({'X-CSRFToken': csrftoken})
    login_data = {'username': username, 'enc_password': enc_password}

    login = session.post('https://www.instagram.com/accounts/login/ajax/', data=login_data, allow_redirects=True)
    session.headers.update({'X-CSRFToken': login.cookies['csrftoken']})

    cookies = login.cookies
    print(login.text)

    session.close()


来源:https://stackoverflow.com/questions/58520305/python-instagram-login-using-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!