Python Instagram Login Using Requests
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 alw
Solution 1:
Currently (January 2021) a working solution to log into Instagram using Python is the following:
deflogin(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 = Nonefor 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()
Solution 2:
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 inprint(login.text)
#In case of refused connectionexcept 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.
Post a Comment for "Python Instagram Login Using Requests"