What cases were added to the Supreme Court’s docket today?

What is this post about?

That Court Crawler Tool I shared a while ago was pretty good at fetching details of decisions from various courts in Nepal (Supreme Court, High Court, District Court and Special Courts). But here’s the deal – that tool only spitted out info about cases that are all wrapped up and done. Sometimes, though, we need to keep tabs on the fresh cases hitting the court’s docket daily so we can keep an eye on them down the line.

So, what if we tweaked things up a bit and got a daily email digest, keeping us in the loop about every case that got the green light in the court’s docket that day? That’d be sweet, right? Well, that’s exactly what this tool is all about now. Right now, it’s only scooping up the daily scoop from the Supreme Court, but guess what? It’s super flexible and can easily do the same dance for all the other courts too. I’m planning to roll out that upgrade sometime soon.

So, in a nutshell, we’re giving the Court Crawler Tool a makeover to not just track the final decisions but also keep us posted on the daily hustle of newly registered cases. And hey, although I am starting with the Supreme Court but very soon I might just hook up all the other courts too within the same tool. Stay tuned!

Can you not find this data on the Supreme Court’s website?

Of course you can find this on the Supreme Court’s website but there is no dedicated method for this. Every day you will need to keep tab of the various case category that gets docketed like “AP”, “CF”, “CI”, “CR”, “DF”, “FN”, “LE”, “MS”, “NF”, “RC”, “RE”, “RI”, “RV”, “SA”, “WF”, “WH”, “WO”, “WS” and the most latest registration number belonging to that category and then go on to scrape the details by constructing your case registration number (e.g. 080-CF-0001) and then tabulate those and make sure you consider from among them only those that got registered today, prepare a email digest and send it to your email id. That’s a lot of work to be done everyday assuming you have the complete foolproof concept of the case registration numbering followed by the Courts. 

How does this work?

Extracting this information from the Supreme Court’s website isn’t a straightforward task. Unfortunately, there isn’t a dedicated method readily available. To achieve this, you’ll need to manually track various case categories such as “AP,” “CF,” “CI,” and so on. Additionally, keeping abreast of the latest registration number within each category is imperative.

Now, the intricate part involves constructing case registration numbers (e.g., 080-CF-0001) and subsequently navigating through the website to extract relevant details. However, the complexity doesn’t end there. You must discern and isolate only those cases that were registered on the current day, a process akin to finding a needle in a digital haystack.

This routine becomes a daily undertaking, assuming you’ve deciphered the intricacies of the court’s case registration numbering system. Undoubtedly, it demands a significant effort, but once you have scripting knowledge you can automate this for daily case tracking. All for the sake of receiving that email digest in your inbox. 

Python, Basic CRUD and Task Scheduler

The Process for Digital Nerds

1. Construction of Registration Numbers (construct_regno):
This function takes a category and a number and constructs a registration number in the format “080-{category}-{number:04d}”. The number is formatted with leading zeros to ensure a consistent length.
2. Reading and Writing Latest Numbers (read_latest_numbers and write_latest_numbers):
These functions read and write the latest case numbers for each category to a text file. The text file, named “latest.txt,” is used to keep track of the latest case numbers for each category. The format in the file is “{category}:{number}”, and the script reads and updates this information.
3. Processing Categories (process_category):
This function performs the following steps for a given category:
Constructs a registration number using the category and the latest number for that category.
Makes a POST request to a specified URL with form data and the constructed registration number.
Parses the HTML content of the response using BeautifulSoup.
Checks if the text “Total 1 Records Found” is present in the HTML.
If found, extracts a specific HTML element and appends it to an output HTML file.
Increments the category’s latest number and constructs a new registration number for the next iteration.
This process continues until no more records are found.
4. Sending Email (send_email):
This function sends an email with the following components:
The HTML content of the output file as the email body.
The output HTML file as an attachment.
The email includes the current date and is sent using the SMTP protocol.
5. Main Loop (main):
The main function orchestrates the entire process:
Defines the URL, form data, categories, and output file name.
Reads the latest numbers from the “latest.txt” file.
Iterates through each category, calling process_category for each.
Writes the updated latest numbers back to the “latest.txt” file.
Reads the HTML content from the output file.
Calls send_email to send an email with the HTML content and the output file as an attachment.

In summary, the script automates the process of checking for new records on a website related to Supreme Court cases, saving relevant information, and notifying a recipient via email with the collected data as an attachment. It uses a combination of web scraping, file I/O, and email functionalities.

The Python Script Itself

Contents of getDailyCaseRegistration.py

            import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import datetime
import os

# Function to construct regno based on category and number
def construct_regno(category, number):
    return f"080-{category}-{number:04d}"

# Function to read the latest numbers from the text file
def read_latest_numbers(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        latest_numbers = {line.split(':')[0].strip(): int(line.split(':')[1]) for line in lines}
    return latest_numbers

# Function to write the latest numbers to the text file
def write_latest_numbers(filename, latest_numbers):
    with open(filename, 'w', encoding='utf-8') as file:
        for category, number in latest_numbers.items():

# Function to make request and save HTML if "Total 1 Records Found" is present
def process_category(url, form_data, category, latest_numbers, output_file):
    number = latest_numbers[category]
    regno = construct_regno(category, number)

    while True:
        form_data['regno'] = regno

        response = requests.post(url, data=form_data)
        response.encoding = 'utf-8'  # Set the encoding to UTF-8
        soup = BeautifulSoup(response.text, 'html.parser')

        if "Total 1 Records Found" in soup.get_text():
            # Extract the specified element
            table_element = soup.select_one('html > body > div:nth-of-type(3) > div > div:nth-of-type(2)')
            # Save HTML with "Total 1 Records Found" and only the specified element
            with open(output_file, 'a', encoding='utf-8') as html_file:
                html_file.write(f"<!-- {regno} - Total 1 Records Found -->\n")
                if table_element:

            # Increment number for the category
            number += 1
            regno = construct_regno(category, number)
            # Update latest number for the category
            latest_numbers[category] = number

# Function to send email with HTML content as the body and output file as an attachment
def send_email(html_content, output_file):
    sender_email = "automation@sushilparajuli.com"
    receiver_email = "parajulishusil@gmail.com"
    smtp_server = "mail.sushilparajuli.com"
    smtp_port = 587  # You might need to adjust this based on your email provider
    smtp_username = sender_email
    smtp_password = "enterYourPasswordHere" ################################################ enter your password here

    subject = f"Cases that got registered today {datetime.datetime.now().strftime('%Y-%m-%d')}"

    # Create message container
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject

    # Attach HTML content to the email
    html_body = MIMEText(html_content, "html")

    # Attach output file as an attachment
    with open(output_file, "rb") as attachment:
        part = MIMEApplication(attachment.read(), Name=os.path.basename(output_file))
        part['Content-Disposition'] = f'attachment; filename="{os.path.basename(output_file)}"'

        # Establish a connection to the SMTP server
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            # Start TLS for security

            # Log in to the SMTP server
            server.login(smtp_username, smtp_password)

            # Send the email
            server.sendmail(sender_email, receiver_email, message.as_string())

        print("Email sent successfully!")

        # Delete the output HTML file
        print(f"Output file '{output_file}' deleted.")

    except Exception as e:
        print(f"Error sending email: {e}")

# Main loop to iterate through categories
def main():
    url = "https://supremecourt.gov.np/lic/sys.php?d=reports&f=case_details"
    form_data = {
        'syy': '',
        'smm': '',
        'sdd': '',
        'mode': 'show',
        'list': 'list',
        'regno': '',
        'tyy': '',
        'tmm': '',
        'tdd': '',
    latest_numbers = read_latest_numbers("latest.txt")

    categories = ["AP", "CF", "CI", "CR", "DF", "FN", "LE", "MS", "NF", "RC", "RE", "RI", "RV", "SA", "WF", "WH", "WO", "WS"]
    output_file = "output.html"

    for category in categories:
        process_category(url, form_data, category, latest_numbers, output_file)

    # Write the latest numbers to the file
    write_latest_numbers("latest.txt", latest_numbers)

    # Read HTML content from the output file
    with open(output_file, "r", encoding="utf-8") as html_file:
        html_content = html_file.read()

    # Send email with HTML content and output file as attachment, then delete the output file
    send_email(html_content, output_file)

if __name__ == "__main__":


Contents of latest.txt which has to be stored in the same folder where your python script is. 


Automation through Windows Task Scheduler

To schedule the above Python script through Task Scheduler in Windows: 

Press Win + S and type “Task Scheduler,” then press Enter. In the Actions pane, click “Create Basic Task…” Follow the wizard to set a name and description. Select a trigger (e.g., daily, weekly) for when you want the script to run. Specify the start date and time based on your preference.

Choose Action: Select “Start a program” and click Next. Browse and select the Python executable (python.exe) as the program. You can find your python executable location by typing “where python” in the command prompt. In “Add arguments,” provide the name of your Python script (e.g. script.py). In “Start in,” provide the path of your script folder (e.g., C:\Path\to\your\script\folder) Review your settings and click Finish.

Now, your Python script will run automatically based on the scheduled triggers you configured in Task Scheduler and every day at the specified time you will receive a daily digest of all the cases that got added to supreme court’s docket on that particular day.