Skip to content

Instantly share code, notes, and snippets.

@s0x90
Created January 2, 2016 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s0x90/7882c0cf7eccab58b732 to your computer and use it in GitHub Desktop.
Save s0x90/7882c0cf7eccab58b732 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from urlparse import urlparse
from settings import INSTAGRAM_USER, INSTAGRAM_PASS, INSTAGRAM_CLIENT_ID, INSTAGRAM_REDIRECT_URI
class InstagramLoginError(Exception):
pass
class InstagramConnector(object):
def __init__(self, user, password, client_id, redirect_uri, login_url=None, authorization_url=None):
self.user = user
self.password = password
self.login_url = login_url or 'https://www.instagram.com/accounts/login/?force_classic_login=&'
self.authorization_url = authorization_url or 'https://api.instagram.com/oauth/authorize/?client_id=%s&redirect_uri=%s&response_type=token'
self.redirect_uri = redirect_uri
self.client_id = client_id
self.session = requests.Session()
def __enter__(self):
return self
def __exit__(self, *args):
self.session.close()
def _get_headers(self):
headers = self.session.headers
headers.update({
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36',
'Referer': "https://www.instagram.com/accounts/login/?force_classic_login=&"
})
return headers
@property
def _login_page_obj(self):
headers = self._get_headers()
response = self.session.get(self.login_url, headers=headers)
return response
@staticmethod
def _get_csrfmiddlewaretoken(page_obj):
soup = BeautifulSoup(page_obj.content, "html.parser")
csrf_token = soup.find("input", {'name': "csrfmiddlewaretoken"}).get('value')
return csrf_token
def execute(self, data, cookies):
headers = self._get_headers()
try:
response = self.session.post(self.login_url, data=data, cookies=cookies,
headers=headers, verify=True, allow_redirects=True)
except requests.ConnectionError:
return {'error': 'Can not connect to the Instagram Login Page'}
return response
def login(self):
if not all((self.user, self.password)):
raise InstagramLoginError("Provided empty Instagram credentials")
login_page_obj = self._login_page_obj
csrf_token = self._get_csrfmiddlewaretoken(login_page_obj)
data = {
'username': self.user,
'password': self.password,
'csrfmiddlewaretoken': csrf_token
}
cookies = login_page_obj.cookies
response = self.execute(data, cookies)
if response.status_code != 200:
raise InstagramLoginError('Can not connect', response.status_code)
return response
def get_url_to_redirect(self):
s = self.authorization_url % (self.client_id, self.redirect_uri)
return s
def _get_url_with_token(self, auth_url):
req = self.session.get(auth_url, allow_redirects=True)
return req.url
def token(self):
url_to_redirect = self.get_url_to_redirect()
url = self._get_url_with_token(url_to_redirect)
parsed_url = urlparse(url)
fragment = parsed_url.fragment
delimeter = fragment.index('=')
return fragment[delimeter+1:]
if __name__ == '__main__':
with InstagramConnector(INSTAGRAM_USER, INSTAGRAM_PASS, INSTAGRAM_CLIENT_ID, INSTAGRAM_REDIRECT_URI) as c:
login = c.login()
token = c.token()
print token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment