Войдите на сайт с помощью python

Я пытаюсь войти на эту страницу с помощью Python. Вот мой код

  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() 

Я пытался использовать запросы. но приведенный выше код не может получить доступ к странице, требующей входа в систему.

Что я делаю неправильно?


person Emil George James    schedule 05.07.2015    source источник


Ответы (1)


Вы неправильно используете строковые значения вместо предполагаемых переменных внутри 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 .: Возвращайтесь, если ищете что-то еще, но подробно опубликуйте то, что вы хотели и что получили!

person devautor    schedule 05.07.2015
comment
Яаа это сработало. благодаря. Но мне нужно распечатать содержимое страницы после входа в систему как текст. Как это сделать ??? - person Emil George James; 06.07.2015
comment
Посмотрите, поможет ли это вам как-использовать-python-to-login-to-a-webpage-and-retrieve-cookies-for -later-usage - person devautor; 06.07.2015
comment
Спасибо за зелень :) - person devautor; 17.07.2015