How can i login in instagram with python requests?

2024/11/16 20:53:20

Hello i am trying to login instagram with python requests library but when i try, instagram turns me "bad requests". İs anyone know how can i solve this problem?

i searched to find a solve for this problem but i didnt find anything. Please help, thanks!

it was working but after some time, it started to turn "bad request"

this is full of my code:

import os
import requests
import getpass
import json
import io
import timeX_SECOND = 60
BASE_URL = "https://www.instagram.com/"
LOGIN_URL = BASE_URL + "accounts/login/ajax/"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; ) Gecko/20100101 Firefox/65.0"
CHANGE_URL = "https://www.instagram.com/accounts/web_change_profile_picture/"
CHNAGE_DATA = {"Content-Disposition": "form-data", "name": "profile_pic","filename": "profilepic.jpg", "Content-Type": "image/jpeg"}
headers = {"Host": "www.instagram.com","Accept": "*/*","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate, br","Referer": "https://www.instagram.com/accounts/edit/","X-IG-App-ID": "936619743392459","X-Requested-With": "XMLHttpRequest","DNT": "1","Connection": "keep-alive",
}
session = requests.Session()
session.headers = {'user-agent': USER_AGENT, 'Referer': BASE_URL}def login():USERNAME = str(input('Username > '))PASSWD = getpass.getpass('Password > ')resp = session.get(BASE_URL)session.headers.update({'X-CSRFToken': resp.cookies['csrftoken']})login_data = {'username': USERNAME, 'password': PASSWD}login_resp = session.post(LOGIN_URL, data=login_data, allow_redirects=True)print(login_resp.text)  # it turns "bad request"time.sleep(100)if login_resp.json()['authenticated']:print("Login successful")else:print("Login failed!")login()# print(login.json())session.headers.update({'X-CSRFToken': login_resp.cookies['csrftoken']})def save():with open('cookies.txt', 'w+') as f:json.dump(session.cookies.get_dict(), f)with open('headers.txt', 'w+') as f:json.dump(session.headers, f)def load():with open('cookies.txt', 'r') as f:session.cookies.update(json.load(f))with open('headers.txt', 'r') as f:session.headers = json.load(f)def change():session.headers.update(headers)try:print("wow"+str(i))with open("./data/wow"+str(i)+".png", "rb") as resp:f = resp.read()print("1")p_pic = bytes(f)print("2")p_pic_s = len(f)print("3")session.headers.update({'Content-Length': str(p_pic_s)})print("4")files = {'profile_pic': p_pic}print("5")r = session.post(CHANGE_URL, files=files, data=CHNAGE_DATA)print("6")if r.json()['changed_profile']:print("Profile picture changed!")else:print("Something went wrong")time.sleep(X_SECOND)except Exception as e:print(e)passtime.sleep(10)if __name__ == "__main__":i = 0try:load()except:login()save()while True:if i == 12:i = 0i += 1change()

AN UPDATE

also the instaloader users are gettin same problem now https://github.com/instaloader/instaloader/issues/615

Answer
link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'time = int(datetime.now().timestamp())
response = requests.get(link)
csrf = response.cookies['csrftoken']payload = {'username': username,'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:{password}','queryParams': {},'optIntoOneTap': 'false'
}login_header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36","X-Requested-With": "XMLHttpRequest","Referer": "https://www.instagram.com/accounts/login/","x-csrftoken": csrf
}login_response = requests.post(login_url, data=payload, headers=login_header)
json_data = json.loads(login_response.text)if json_data["authenticated"]:print("login successful")cookies = login_response.cookiescookie_jar = cookies.get_dict()csrf_token = cookie_jar['csrftoken']print("csrf_token: ", csrf_token)session_id = cookie_jar['sessionid']print("session_id: ", session_id)
else:print("login failed ", login_response.text)

You can find a complete guide here:

Share a post into your Instagram account using the requests library.

https://en.xdnf.cn/q/71628.html

Related Q&A

How to abstract away command code in custom django commands

Im writing custom django commands under my apps management/commands directory. At the moment I have 6 different files in that directory. Each file has a different command that solves a unique need. How…

Python one-liner (converting perl to pyp)

I was wondering if its possible to make a one-liner with pyp that has the same functionality as this.perl -l -a -F, -p -eif ($. > 1) { $F[6] %= 12; $F[7] %= 12;$_ = join(q{,}, @F[6,7]) }This takes i…

Getting symbols with Lark parsing

Im trying to parse a little pseudo-code Im writing and having some trouble getting values for symbols. It parses successfully, but it wont return a value the same as it would with "regular" …

Why cant I connect to my localhost django dev server?

Im creating a django app and in the process of setting up my local test environment. I can successfully get manage.py runserver working but pointing my browser to any variation of http://127.0.0.1:8000…

How to use L2 pooling in Tensorflow?

I am trying to implement one CNN architecture that uses L2 pooling. The reference paper particularly argues that L2 pooling was better than max pooling, so I would like to try L2 pooling after the acti…

Abstract base class is not enforcing function implementation

from abc import abstractmethod, ABCMetaclass AbstractBase(object):__metaclass__ = ABCMeta@abstractmethoddef must_implement_this_method(self):raise NotImplementedError()class ConcreteClass(AbstractBase)…

Create dataframe from dictionary of list with variable length

I have a dictionary of list which is like - from collections import defaultdict defaultdict(list,{row1: [Affinity],row2: [Ahmc,Garfield,Medical Center],row3: [Alamance,Macbeth],row4: [],row5: [Mayday]}…

How to standardize ONE column in Spark using StandardScaler?

I am trying to standardize (mean = 0, std = 1) one column (age) in my data frame. Below is my code in Spark (Python):from pyspark.ml.feature import StandardScaler from pyspark.ml.feature import VectorA…

Pandas Dataframe - select columns with a specific value in a specific row

I want to select columns with a specific value (say 1) in a specific row (say first row) for Pandas Dataframe

PermissionError: [Errno 13] Permission denied in Django

I have encountered a very strange problem.Im working with django, I create a directory on server, and try to save pickle file into it, this way:with open(path, wb) as output: pickle.dump(obj, output, p…