Reputation:
I'm tyring to login to a website login.php
using Python requests module.
If the attempt is successful, the page will be redirected to index.php
If not, it remains there in login.php
.
I was able to do the same with mechanize
module.
import mechanize
b = mechanize.Browser()
url = 'http://localhost/test/login.php'
response = b.open(url)
b.select_form(nr=0)
b.form['username'] = 'admin'
b.form['password'] = 'wrongpwd'
b.method = 'post'
response = b.submit()
print(response.geturl())
if response.geturl() == url:
print('Failed')
else:
print('OK')
If login/password is correct
user@linux:~$ python script.py
http://localhost/test/index.php
OK
user@linux:~$
If login/password is wrong
user@linux:~$ python script.py
http://localhost/test/login.php
Failed
user@linux:~$
My question is how to do the same with requests
module?
I was trying different approach here, but none of them work.
Upvotes: 4
Views: 15545
Reputation: 3390
I've took the code from your question and modified it:
import requests
url = 'http://localhost/test/login.php'
values = {'username': 'admin', 'password': 'wrongpwd'}
r = requests.post(url, data=values)
print(r.url) # prints the final url of the response
You can know it's a sure thing because it's documented in the source code. All I've done is opened the definition of the Response
class.
Now, back to your original question.
Python requests module to verify if HTTP login is successful or not
It depends on whether the website is properly implemented.
When you send a form, any website replies to you with an HTTP response, which contains a status code. A properly implemented website returns different status codes depending on the stuff you've sent. Here's a list of them. If everything is honky-dory, the status code of the response will be 200
:
import requests
url = 'http://localhost/test/login.php'
values = {'username': 'admin', 'password': 'wrongpwd'}
r = requests.post(url, data=values)
print(r.status_code == 200) # prints True
If the user entered the wrong credentials, the status code of the response will be 401
(see the list above). Now, if a website is not implemented properly, it will respond with 200
anyway and you'll have to guess whether the login is successful based on other things, such as response.content
and response.url
.
Upvotes: 2