Login to a website using python

Emil George James picture Emil George James · Jul 5, 2015 · Viewed 7.7k times · Source

I am trying to login to this page using Python.Here is my code

  from urllib2 import urlopen                        
  from bs4 import BeautifulSoup
  import requests
  import sys


  URL= 'http://coe2.annauniv.edu/result/index.php'
  soup = BeautifulSoup(urlopen(URL))

  for hit in soup.findAll(attrs={'class' : 's2'}):
  print hit.contents[0].strip()


  RegisterNumber = raw_input("enter the register number")
  DateofBirth = raw_input("enter the date of birth [DD-MM-YYYY]")
  login_input = raw_input("enter the what is()?")

 def main():
    # Start a session so we can have persistant cookies
     session = requests.session()

# This is the form data that the page sends when logging in
login_data = {
    'register_no':'RegisterNumber',
    'dob':'DateofBirth',
    'security_code_student' :'login_input',
    'gos': 'Login',
}

# Authenticate
r = session.post(URL, data=login_data)

# Try accessing a page that requires you to be logged in
r = session.get('http://coe2.annauniv.edu/result/students_corner.php')

 if __name__ == '__main__':
      main() 

i tried using requests .but the above code can't accessed the page that requires to be login.

What am I doing wrong?

Answer

devautor picture devautor · Jul 5, 2015

You are incorrectly using string values instead of the intended variables inside login_data.

from urllib2 import urlopen                        
from bs4 import BeautifulSoup
import requests
import sys

URL= 'http://coe2.annauniv.edu/result/index.php'
soup = BeautifulSoup(urlopen(URL))
#print soup.prettify()

for hit in soup.findAll(attrs={'class' : 's2'}):
    print hit.contents[0].strip()

RegisterNumber = raw_input("Enter the registration number: ")
DateofBirth = raw_input("Enter the date of birth [DD-MM-YYYY]: ")
login_input = raw_input("Enter the what is()? ")

def main():
    # Start a session so we can have persistant cookies

    # Session() >> http://docs.python-requests.org/en/latest/api/#request-sessions
    session = requests.Session() 

    # This is the form data that the page sends when logging in

    # You are wrongly using string values instead of the intended variables here that is RegisterNumber and not 'RegisterNumber'
    login_data = {
    'register_no': RegisterNumber,
    'dob': DateofBirth,
    'security_code_student': login_input,
    'gos': 'Login',
    }
    print login_data

    # Authenticate
    r = session.post(URL, data = login_data)
    # Try accessing a page that requires you to be logged in
    r = session.get('http://coe2.annauniv.edu/result/students_corner.php')
    print r

if __name__ == '__main__':
    main()

P.S.: Get back if you are looking for something else, but post what you wished and what you got elaborately!