w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Log in to website using Python Requests module

You will need to add the username and password as authentication header to the request. You can find more details here: http://docs.python-requests.org/en/latest/user/advanced/

You could simply use s.auth = (username, password). Thats the easiest way to implement it. But if you want to add it into the header yourself, you will first have to build the header. The authorization header contains the username and password which need to be b64encoded. For example:

[In python3]

from base64 import b64encode
import requests

username = input('Please enter your username: ')
password = input('Please enter your password: ')

authHandler = '{0}:{1}'.format(username, password).encode()
authHeader = {'Authorization' : 'Basic
{0}'.format(b64encode(authHandler).decode("ascii"))}
with requests.Session() as s:
    con = s.post('somewebsite.com', headers=authHeader)

[In python2.7]

from base64 import b64encode
import requests

username = raw_input('Please enter your username: ')
password = raw_input('Please enter your password: ')

authHandler = '{0}:{1}'.format(username, password)
authHeader = {'Authorization' : 'Basic {0}'.format(b64encode(authHandler))}
with requests.Session() as s:
    con = s.post('somewebsite.com', headers=authHeader)




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.