本文介绍了使用python和请求进行Instagram身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为我的项目创建instagram登录表单.我已经编写了此代码,但无法正常工作.请求后,我需要获取"sessionid" cookie
I need to create the instagram login form for my project. I've written this code but it doesnt work correctly. I need to get the 'sessionid' cookie after the request
def authorize_inst():
url = 'https://www.instagram.com/'
url_main = url + 'accounts/login/ajax/'
req1 = requests.get(url)
print(req1.headers)
print(req1.cookies['csrftoken'])
print('-----')
auth = {'username':'login','password':'pass'}
req2 = requests.post(url_main,cookies={'csrftoken':req1.cookies['csrftoken']},data=auth,allow_redirects=True)
print(req2.headers)
print(req2.cookies)
以下是响应标头:
`{'Content-Type': 'text/html', 'X-Frame-Options': 'SAMEORIGIN', 'Cache-Control': 'private, no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT', 'Vary': 'Cookie, Accept-Language', 'Content-Language': 'en', 'Access-Control-Allow-Origin': 'https://www.instagram.com/', 'Date': 'Sat, 17 Feb 2018 08:46:12 GMT', 'Strict-Transport-Security': 'max-age=86400', 'Set-Cookie': 'rur=FTW; Path=/, csrftoken=KSGEZBQrpQBQ8srEcK98teilzOsndDcF; expires=Sat, 16-Feb-2019 08:46:12 GMT; Max-Age=31449600; Path=/; Secure, mid=Wofr1AAEAAGPK-9pKoyWokm4jRo8; expires=Fri, 12-Feb-2038 08:46:12 GMT; Max-Age=630720000; Path=/', 'Connection': 'keep-alive', 'Content-Length': '21191'`}
以及req2.content
中的零件代码:
<title>\n Page Not Found • Instagram\n </title>
出什么问题了?预先谢谢你.
What is the problem? Thank you in advance.
推荐答案
如果使用 requests.Session()
,则不需要cookie
标头.
对解决方案进行一些更改;您可以使用此:
Making a few changes to your solution; you can use this:
import requests
url = 'https://www.instagram.com/accounts/login/'
url_main = url + 'ajax/'
auth = {'username': 'login', 'password': 'pass'}
headers = {'referer': "https://www.instagram.com/accounts/login/"}
with requests.Session() as s:
req = s.get(url)
headers['x-csrftoken'] = req.cookies['csrftoken']
s.post(url_main, data=auth, headers=headers)
# Now, you can use 's' object to 'get' response from any instagram url
# as a logged in user.
r = s.get('https://www.instagram.com/accounts/edit/')
# If you want to check whether you're getting the correct response,
# you can use this:
print(auth['username'] in r.text) # which returns 'True'
这篇关于使用python和请求进行Instagram身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!