Accessing password-protected pages
Sometimes a web page is not open to the public but protected in some way. The simplest aspect of protection is to use basic HTTP authentication, which is integrated into virtually every web server and implements a user/password schema.
Getting ready
We can test this kind of authentication in https://httpbin.org.
It has a path, /basic-auth/{user}/{password}
, which forces authentication, with the user and password stated. This is very handy for understanding how authentication works.
How to do it...
- Import
requests
:>>> import requests
- Make a
GET
request to the URL with the wrong credentials. Notice that we set the credentials on the URL to beuser
andpsswd
:>>> requests.get('https://httpbin.org/basic-auth/user/psswd', auth=('user', 'psswd')) <Response [200]>
- Use the wrong credentials to return a 401 status...