简体   繁体   English

Instagram 使用 python-requests、cookies 登录错误

[英]Instagram login with python-requests, cookies error

im trying to login to Instagram with help of requests...im following this answer https://stackoverflow.com/a/65892587/13419605我试图在请求的帮助下登录 Instagram ......我按照这个答案https://stackoverflow.com/a/65892587/13419605

this work great on my laptop but, server-side have this error.这在我的笔记本电脑上很好用,但是服务器端有这个错误。

env:环境:

  1. Ubuntu 18.04 Ubuntu 18.04
  2. python 3.6.9 python 3.6.9
  3. requests 2.25.1请求 2.25.1

code:代码:

import requests
import datetime

session = requests.session()
def login(session, username, password):
    """Login to Instagram"""

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

    
    # set a cookie that signals Instagram the "Accept cookie" banner was closed
    session.cookies.set("ig_cb", "2")
    session.headers.update({'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\
 Chrome/59.0.3071.115 Safari/537.36'})
    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()


login(session, 'username', 'password')

error:错误:

Traceback (most recent call last):
  File "login.py", line 38, in <module>
    login(session, 'username', 'password')
  File "login.py", line 30, in login
    session.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
  File "/django/venv/lib/python3.6/site-packages/requests/cookies.py", line 328, in __getitem__
    return self._find_no_duplicates(name)
  File "/django/venv/lib/python3.6/site-packages/requests/cookies.py", line 399, in _find_no_duplicates
    raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"

This is because there is no csrftoken in login cookies.这是因为登录cookies中没有csrftoken。 Instagram block requests from severs. Instagram 阻止来自服务器的请求。 Using proxy might help.使用代理可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM