Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get Indian Railways Station code Using Python
Web scraping is one of the many powerful uses for Python. In this article, we'll discover how to extract Indian Railways station codes using Python. Each Indian railway station has a unique identification code used for ticket reservations, train schedules, and other railway information.
Installation
First, we need to install the required libraries. Requests is used for sending HTTP requests, while Beautiful Soup is used for parsing HTML content.
To install the required packages, open your terminal and run
pip install requests pip install beautifulsoup4
Algorithm
Define a function
get_htmlthat takes a URL as input and returns HTML contentCreate headers dictionary with user agent information to mimic a browser request
Use
requests.get()to make HTTP GET request and return response textDefine
get_station_codefunction that takes station name as inputConstruct URL by concatenating station name to the base URL
Parse HTML data using BeautifulSoup
Extract station code from the table with class
extrtableReturn the station code text from the last
<b>tag
Example
import requests
from bs4 import BeautifulSoup
# Function to get HTML data from a URL
def get_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
}
response = requests.get(url, headers=headers)
return response.text
# Main function to get station code from mapsofindia.com
def get_station_code(station_name):
# Construct URL for the station page
url = f"https://www.mapsofindia.com/railways/station-code/{station_name}.html"
# Get HTML data for the station page
html_data = get_html(url)
# Parse HTML data using BeautifulSoup
soup = BeautifulSoup(html_data, 'html.parser')
# Extract station code from HTML data
station_code = soup.find("table", class_="extrtable").find_all('b')[-1].get_text()
# Return station code
return station_code
# Example usage
station_name = "pune-junction"
station_code = get_station_code(station_name)
print(f"Station Code for {station_name.title()} is {station_code}")
station_name = "new-delhi"
station_code = get_station_code(station_name)
print(f"Station Code for {station_name.title()} is {station_code}")
Output
Station Code for Pune-Junction is PUNE Station Code for New-Delhi is NDLS
How It Works
The script uses two main functions to extract railway station codes:
get_html() Function: This function sends an HTTP GET request to the specified URL with proper headers to mimic a browser request. It returns the HTML content of the webpage.
get_station_code() Function: This function constructs the URL for the station page, retrieves the HTML data, and parses it using BeautifulSoup. It locates the table with class extrtable and extracts the station code from the last <b> tag in the table.
Error Handling
For production use, consider adding error handling to manage network issues or missing station data ?
def get_station_code_safe(station_name):
try:
url = f"https://www.mapsofindia.com/railways/station-code/{station_name}.html"
html_data = get_html(url)
soup = BeautifulSoup(html_data, 'html.parser')
table = soup.find("table", class_="extrtable")
if table:
station_code = table.find_all('b')[-1].get_text()
return station_code
else:
return "Station not found"
except Exception as e:
return f"Error: {str(e)}"
Applications
This code can be extended for various railway applications:
Building ticket booking applications where users can search stations by name
Creating train schedule lookup tools
Developing railway information systems
Building mobile apps for railway services
Conclusion
We've learned how to extract Indian Railways station codes using Python web scraping. This technique combines requests for HTTP communication and BeautifulSoup for HTML parsing. The code can be enhanced with error handling and extended for various railway applications.
