DEV Community

Sourav
Sourav

Posted on • Edited on

Retrieve Vaccine Slots in your locality (Python Web-Scrapping)

I know it is hard to get a vaccine slot. I have been trying to get a slot for the last two weeks; still have not got it. Therefore I decided to make a python script that will notify me about the vaccination slots.

For this, we will use the APIs provided by our Indian Government and scrap the page. If you try to do a lot of requests to the server, your IP address may be blocked. BEWARE!!!!!!!!!!!

What is Web Scraping

Web scraping is the process of using bots to extract content and data from a website.

Cowin-API

You can check the APIs from this page. (Link)

Let’s have a look at the response for the network which we are going to make. We have to create a model to extract that information.

Demo API call: https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=110001&date=23-05-2021

We have to find the available_capacity field for each session in each centre.

Coding part

First, install the requests and plyer library.

pip install requests and pip install plyer

Import these libraries, they will be needed. requests is used to make HTTP requests, plyer is used to send desktop notifications. time and datetime are used to handle date-time related things, need to convert them into appropriate formats.

import requests
import time
from datetime import datetime,timedelta
from plyer import notification
Enter fullscreen mode Exit fullscreen mode

Now, we will define some parameters which will be used for searching. You have to enter the age, pin codes and the number of days you want to search for. The API allows us to search for availability for the next 7 days.

user_age = 55
pincodes=["782411","782410"]
num_days = 6
Enter fullscreen mode Exit fullscreen mode

We also have to convert to the dates into a suitable format so that we can make the API call. We extract today’s date from datetime and convert the next num_days accordingly.

actual = datetime.today()
list_format = [actual + timedelta(days=i) for i in range(num_days)]
actual_dates = [i.strftime("%d-%m-%Y") for i in list_format]
Enter fullscreen mode Exit fullscreen mode

Now comes the main part. We have to search for all the pincodes for all the given dates. Also, the search is needed to be done for all the centres for all the sessions. If any conditions are satisfied, then we will print that result. That result will be sent as a notification to the desktop. After the search is completed, we will wait for 5 minutes (use sleep function) and continue searching again.

while(True) :
    availbleCenters = 0

    #We have to search for all pincodes for all the given dates
    for pincode in pincodes:
        for date in actual_dates:
            #The API to hit for our operation
            URL = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={pincode}&date={date}"
            header = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}

            result = requests.get(URL, headers=header)
            #If the response is 200 then proceed
            if result.ok:
                response_json = result.json()
                #We have to search for available capacity in each session for each center
                for center in response_json['centers']:
                    for session in center['sessions']:
                        #If the condition is satisfied like the available capacity is not zero and age limit is also satisfied then print them
                        if (session['available_capacity']>0 and session['min_age_limit']<=user_age and session["date"] == date ):
                            availbleCenters = availbleCenters+1
                            print('Center Name : ' , center['name'])
                            print('Available slots : ' , session['available_capacity'])
                            print('Pincode : ' , pincode)
                            print('Vaccine Name : ' , session['vaccine'])
                            print('Date : ', session['date'])
                            print('----------------------------------')

                            centerName = center['name']
                            availbleSlots = session['available_capacity']
                            dateOfSlot = session['date']
                            vaccineName = session['vaccine']
                            #plyer is used here to notify people in desktop.
                            notification.notify(
                                title="Vaccine Slots Availble",
                                # the body of the notification
                                message=f"Center Name : {centerName} \n Availble slots : {availbleSlots} \n Vaccine Name : {vaccineName} \n Date : {dateOfSlot}",
                                #You can add a icon here also in the .ico format
                                # the notification stays for 5sec
                                timeout=5
                            )


            else:
                print("No Response")

    if availbleCenters==0:
        print("No availble slots in these areas...")
        notification.notify(
            title="No Vaccine Slots are available",
            # the body of the notification
            message="Sorry, there is no available slot in your area",
            # You can add a icon here also in the .ico format
            # the notification stays for 5sec
            timeout=5
        )
    else:
        print(f"Hurray. Found {availbleCenters} results...")
    #The process will resume after 300 seconds. That means we will make the APi call again after 5 minutes.
    time.sleep(300)
    print("Waited for 5 minutes. Start searching again")
Enter fullscreen mode Exit fullscreen mode

After you run this script, you will receive notifications every 5 minutes if there is any available slot in your area. Hurray!!!!! We have completed the work.

The notification will be shown like this.

The results will also be printed on the console just like this.

If there is no available slot in those pin codes, you will receive “NO RESPONSE” on the console. You will receive a notification stating no vaccine slots available. You can easily tweak the time for notifications.pincodes and days. Go ahead and play with it.

The complete work can be found here.

Cowin-Notifier

This is a python script which can notify you about vaccination available slots. It uses the API provided by CoWIN and fetches available slots for vaccination. You can input your pincodes(multiple) and number of days you want to fetch and it will notify you about the slots. Pincode, number of days and search time can be changed from the script.

Full Setup Guide

You have to install multiple packages for it.

  1. Install requests (Used for make HTTP requests)
    pip install requests
    
  2. Install Plyer (Used for sending desktop notifications)
    pip install plyer 
    

You can find the full tutorial here.

Top comments (0)