0

Possible Duplicate:
How to “log in” to a website using Python’s Requests module?

I'm programming an application in python 3.2.3, and I don't know how to login to a website. I need to login... and save cookies(I think), but everything I tried doesn't work.

I had try Requests, but no luck. My webpage is running on localhost (it's just simple login form).

FORM:
    <form method="post" action="">
            <input type="text" name="uname" placeholder="Uporabnisko ime:"/>
            <input type="password" name="password" placeholder="Geslo:"/>
            <input type="submit" value="Send"/>
    </form>

Python:

import requests
payload = {'uname': 'name', 'password': 'pswd123'}
r = requests.post('http://localhost/python', data=payload)

This do nothing. How to post name and username.. Thanks for reply.

Community
  • 1
  • 1
What
  • 83
  • 1
  • 2
  • 6
  • 1
    Can you expand on the errors you're facing? Since you're running the website on localhost, I'd suggest finding a way to get some debug info from the sever. – TimD Jan 12 '13 at 21:18
  • If I login, my SQL script will save to database something.. and there I see, my python script doesn't work for login. If I put my website on internet it's the same. So I think it's not problem on localhost. I don't understand very good this dictionary, is key id from HTML form right? And.. what is the result of requests.post()? How to look if I'm succesfuly logged in? – What Jan 12 '13 at 22:25

1 Answers1

6

To instruct python requests to "retain cookies in a login session", use requests.session:

import requests
session = requests.session()
payload = {'uname': 'name', 'password': 'pswd123'}
r = session.post('http://localhost/python', data=payload)
r = session.get('http://localhost/authenticated/resource')
#   ^^^^^^^
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • How to look if I'm succesfuly logged in and my session is saved? – What Jan 13 '13 at 18:50
  • you can examine the return value of `session.post` as you would any other request to see what the response status or content was, or if you redirected in an unexpected way. – SingleNegationElimination Jan 13 '13 at 23:26
  • i have succesfully loged in.. but then my session is gone.. I can get the logged source code, but if I do something then my session is gone. – What Jan 15 '13 at 17:29
  • 1
    I think it should be `session = requests.session()` (i.e. function call)? – Roberto Dec 02 '18 at 16:47