Python Instagram 使用请求登录 [英] Python Instagram login using requests
问题描述
我正在尝试使用 python 登录 Instagram.我能够获得 csrf 令牌,但 requests.Session().post()
似乎没有将登录数据正确发布到网站.我总是得到 class="no-js not-logged-in client-root"
.我已经搜索了一段时间,还尝试登录一些似乎有效的随机站点.在登录方法中,我只是启动一个 requests.Session()
并向 https://www.instagram.com/accounts/login/ 使用登录名和密码作为 data
参数.
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)
另外,请不要告诉我使用 Selenium,我绝对想通过请求来使用它.
Also please don't tell me to use Selenium I strictly want to do it with requests.
推荐答案
目前(2021 年 1 月)使用 Python 登录 Instagram 的可行解决方案如下:
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()
这篇关于Python Instagram 使用请求登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!