Skip to content

Instantly share code, notes, and snippets.

@nikhilweee
Last active February 25, 2024 14:12
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save nikhilweee/9efd9731880104dd00ecf2ed8effacc5 to your computer and use it in GitHub Desktop.
Save nikhilweee/9efd9731880104dd00ecf2ed8effacc5 to your computer and use it in GitHub Desktop.
Get vehicle info from an Indian registration number
import sys
import requests
from bs4 import BeautifulSoup, SoupStrainer
home_url = 'https://parivahan.gov.in/rcdlstatus/'
post_url = 'https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml'
# Everything before the last four digits: MH02CL
first = sys.argv[1]
# The last four digits: 0555
second = sys.argv[2]
r = requests.get(url=home_url)
cookies = r.cookies
soup = BeautifulSoup(r.text, 'html.parser')
viewstate = soup.select('input[name="javax.faces.ViewState"]')[0]['value']
data = {
'javax.faces.partial.ajax':'true',
'javax.faces.source': 'form_rcdl:j_idt32',
'javax.faces.partial.execute':'@all',
'javax.faces.partial.render': 'form_rcdl:pnl_show form_rcdl:pg_show form_rcdl:rcdl_pnl',
'form_rcdl:j_idt32':'form_rcdl:j_idt32',
'form_rcdl':'form_rcdl',
'form_rcdl:tf_reg_no1': first,
'form_rcdl:tf_reg_no2': second,
'javax.faces.ViewState': viewstate,
}
r = requests.post(url=post_url, data=data, cookies=cookies)
soup = BeautifulSoup(r.text, 'html.parser')
table = SoupStrainer('tr')
soup = BeautifulSoup(soup.get_text(), 'html.parser', parse_only=table)
print(soup.get_text())

Programmatically extract owner info from Indian registration numbers

Usage

$ python registration_info.py MH02CL 0555
Registration No:
MH02CL0555
Registration Date:
20-Jan-2012

Chasi No:
WBAKB42080CY83879
Engine No:
16257849

Owner Name: 
SHAH RUKH KHAN

Vehicle Class: 
LMVIMP
Fuel Type:
PETROL

Maker Model:
BMW INDIA PVT. LTD., BMW 740 L I PETROL

Requirements

requests
beautifulsoup4
@Mastan1301
Copy link

Mastan1301 commented Jul 20, 2019 via email

@githubsrinath
Copy link

This is fake. Because MH02CL0555 this vehicle owner name is SHAHNAZ LALARUKH Not SHAH RUKH KHAN.
And Gov portal did not give you the full chassis number they show us "WBAKB42080CYXXXXX".
img
Its indian government website and not Fake! Sharukh khan has sold the car long time back... hence you seeing the latest owner! :)

@kartikbb
Copy link

Can someone confirm that the java code is working? I tried but it is not working for me.

@archi14
Copy link

archi14 commented Aug 15, 2019

PrimeFaces.cw("InputText","widget_form_rcdl_j_idt35_CaptchaID",{id:"form_rcdl:j_idt35:CaptchaID"});
how to resolve this error
still getting this error.

@ckenny
Copy link

ckenny commented Aug 23, 2019

Can someone confirm that the java code is working? I tried but it is not working for me.

Hi,

I tried and its working for me. Here is my version based on the source code provided by https://gist.github.com/githubsrinath/560e2382cb3f84e421f8cf14e5e912b0#file-03-java-or-android

https://github.com/ckenny/IndianVehicleNumberChecker/blob/master/VehicleNumberChecker.java

~KC

@vihatsoft
Copy link

Captcha Error:

PrimeFaces.cw("InputText","widget_form_rcdl_j_idt38_CaptchaID",{id:"form_rcdl:j_ idt38:CaptchaID"});

@praddy26
Copy link

praddy26 commented Sep 1, 2019

Getting captcha error:

PrimeFaces.cw("InputText","widget_form_rcdl_j_idt45_CaptchaID",{id:"form_rcdl:j_idt45:CaptchaID"});

@anmolrajpal
Copy link

anmolrajpal commented Sep 24, 2019

This doesn't work for me. However, I developed a better version which is definitely helping. But it still misses something. Check my repo
'Vehicle-info' on GitHub ===>>> https://github.com/anmolrajpal/vehicle-info
Please contribute to my repo. Though I'm pasting my code here.

Python Script - Vehicle-info

import pytesseract
import argparse
import sys
import re
import os
import requests
import cv2
import json 
import numpy as np
from time import sleep
try:
    import Image
except ImportError:
    from PIL import Image, ImageEnhance
from bs4 import BeautifulSoup, SoupStrainer
from urllib import urlretrieve
from io import BytesIO


app_url = 'https://vahan.nic.in/nrservices/faces/user/searchstatus.xhtml'
captcha_image_url = 'https://vahan.nic.in/nrservices/cap_img.jsp'
number = sys.argv[1]

#MARK: Get Request to get webpage elements like textFields, image, etc
r = requests.get(url=app_url)
cookies = r.cookies
soup = BeautifulSoup(r.text, 'html.parser')

#MARK: ViewState contains token which needs to be passed in POST Request
# ViewState is a hidden element. Open debugger to inspect element 
viewstate = soup.select('input[name="javax.faces.ViewState"]')[0]['value']

#MARK: Get Request to get Captcha Image from URL
## Captcha Image Changes each time the URL is fired
iresponse = requests.get(captcha_image_url)
img = Image.open(BytesIO(iresponse.content))
img.save("downloadedpng.png")

def resolve(img):
	enhancedImage = enhance()
	return pytesseract.image_to_string(enhancedImage)

def enhance():
	img = cv2.imread('downloadedpng.png', 0)
	kernel = np.ones((2,2), np.uint8)
	img_erosion = cv2.erode(img, kernel, iterations=1)
	img_dilation = cv2.dilate(img, kernel, iterations=1)
	erosion_again = cv2.erode(img_dilation, kernel, iterations=1)
	final = cv2.GaussianBlur(erosion_again, (1, 1), 0)
	return final


print('Resolving Captcha')
captcha_text = resolve(img)
extracted_text = captcha_text.replace(" ", "").replace("\n", "")
print("OCR Result => ", extracted_text)
print(extracted_text)

# MARK: Identifying Submit Button which will be responsible to make POST Request
button = soup.find("button",{"type": "submit"})


encodedViewState = viewstate.replace("/", "%2F").replace("+", "%2B").replace("=", "%3D")

# MARK: Data, which needs to be passed in POST Request | Verify this manually in debugger
data = {
	'javax.faces.partial.ajax':'true',
	'javax.faces.source': button['id'],
	'javax.faces.partial.execute':'@all',
	'javax.faces.partial.render': 'rcDetailsPanel resultPanel userMessages capatcha txt_ALPHA_NUMERIC',
	button['id']:button['id'],
	'masterLayout':'masterLayout',
	'regn_no1_exact': number,
	'txt_ALPHA_NUMERIC': extracted_text,
	'javax.faces.ViewState': viewstate,
	'j_idt32':''
}
# MARK: Data in Query format.. But not in use for now
query = "javax.faces.partial.ajax=true&javax.faces.source=%s&javax.faces.partial.execute=%s&javax.faces.partial.render=rcDetailsPanel+resultPanel+userMessages+capatcha+txt_ALPHA_NUMERIC&j_idt42=j_idt42&masterLayout=masterLayout&j_idt32=&regn_no1_exact=%s&txt_ALPHA_NUMERIC=%s&javax.faces.ViewState=%s"%(button['id'], '%40all', number, extracted_text, encodedViewState)


# MARK: Request Headers which may or may not needed to be passed in POST Request
# Verify in debugger
headers = {
	'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
	'Accept': 'application/xml, text/xml, */*; q=0.01',
	'Accept-Language': 'en-us',
	'Accept-Encoding': 'gzip, deflate, br',
	'Host': 'vahan.nic.in',
	'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15',
	'Cookie': 'JSESSIONID=%s; SERVERID_7081=vahanapi_7081; SERVERID_7082=nrservice_7082' % cookies['JSESSIONID'],
	'X-Requested-With':'XMLHttpRequest',
	'Faces-Request':'partial/ajax',
	'Origin':'https://vahan.nic.in',
	'Referer':'https://vahan.nic.in/nrservices/faces/user/searchstatus.xhtml',
    'Connection':'keep-alive'
    # 'User-Agent': 'python-requests/0.8.0',
    # 'Access-Control-Allow-Origin':'*',
}
print(headers)

print("\nCookie JSESSIONID => ", cookies['JSESSIONID'])
print("\nData => \n")
print(data)

# MARK: Added delay
sleep(2.0)



#MARK: Send POST Request 
postResponse = requests.post(url=app_url, data=data, headers=headers, cookies=cookies)
print("\nPOST Request -> Response =>\n")
print(postResponse)

rsoup = BeautifulSoup(postResponse.text, 'html.parser')
print("Mark: postResponse soup => ")
print(rsoup.prettify())

#MARK: Following code finds tr which means <table> element from html response
# the required response is appended in <table> only. Verify it in debugger
table = SoupStrainer('tr')
tsoup = BeautifulSoup(rsoup.get_text(), 'html.parser', parse_only=table)

print("Table Soup => ")
print(tsoup.prettify())
#MARK: Result Table not appending to the response data
#Fix Needed

Run Script from Terminal or CMD
>>> python vehicle-info.py MH04GM9660
Hope it helps!

@Shiba-Kar
Copy link

The above code is now useless the site has used captcha unless and untill we enter the correct code there is no way we can scrap the data. However @anmolrajpal solution works I guess as he is using OpenCV to convert the captcha to text.

@Sandhya-VA
Copy link

tried running the revised code but still getting some error help me out.
error:
Traceback (most recent call last):
File "owner.py", line 14, in
viewstate = soup.select('input[name="javax.faces.ViewState"]')[0]['value']
IndexError: list index out of range

@chauhanvipul87
Copy link

Can someone confirm that the java code is working? I tried but it is not working for me.

Hi,

I tried and its working for me. Here is my version based on the source code provided by https://gist.github.com/githubsrinath/560e2382cb3f84e421f8cf14e5e912b0#file-03-java-or-android

https://github.com/ckenny/IndianVehicleNumberChecker/blob/master/VehicleNumberChecker.java

~KC

Excellent. It worked like a charm

@trishantpahwa
Copy link

trishantpahwa commented Sep 19, 2020

I hope what you actually require can be found here with a better implementation.

Also, here is a video tutorial on how to use it.

P.S: This one doesn't require decoding captchas 🔫 👮, and forming requests is also quite easy.
Hope it helps! 😃


Project deprecated now. :(

@Jeet0027
Copy link

Jeet0027 commented Sep 20, 2020

I hope what you actually require can be found here with a better implementation.

Also, here is a video tutorial on how to use it.

P.S: This one doesn't require decoding captchas 🔫 👮, and forming requests is also quite easy.
Hope it helps! 😃

Great work!

Thanks a lot,
Can you confirm if this api is going to persist for life long.
I doubt what if you remove it tomorrow

@trishantpahwa
Copy link

trishantpahwa commented Sep 21, 2020

Kudos @Jeet0027,

I appreciate your feedback. 😄 🦁

Not sure whether it is going to exist life long.

You see it has been made in correspondence to the results it receives from an official website of Indian Government, that regulates details about Indian vehicles. If one is updated the other has to be updated too.

However, I think it would at least be in a working condition for at least 8+ years.

Else, you would be notified on the discord channel, and the documentation itself if there is any update regarding the same, or in case it gets deprecated.

Thanks


Project deprecated now. :(

@Hariharan-Ramanathan
Copy link

not showing any error but at the same time no output is getting printed.....Please help me with this
Screenshot from 2020-12-12 18-43-02

@faizalsha
Copy link

not showing any error but at the same time no output is getting printed.....Please help me with this
Screenshot from 2020-12-12 18-43-02

same here nothing getting printed. And still, I don't understand how this solves the captcha.

@vipinrthakur
Copy link

Can someone please share the updated code?

seems 'https://parivahan.gov.in/rcdlstatus/?pur_cd=102' and 'https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml' are not working anymore.

Thanks

@anmolrajpal
Copy link

This is bad. I wish there's an alternative. My project idea got burnt now.

@AndroidSoftClub
Copy link

Yes is Work

@vish1234-art
Copy link

it shows index out of value

@Shashwat-05
Copy link

it shows index out of value

check whether the query u gave is right !1
and yes , if anyone found better api source
, mention here

@ashishbudhraja
Copy link

You can Check once for www.apiclub.in

@krishna2917
Copy link

www.apiclub.in
High price per request

@chiru952
Copy link

i want to api vahan info data base

@dhanish-jose
Copy link

You can Check once for www.apiclub.in

ApiClub is asking for 10K just for account activation which is non refundable

@dhanish-jose
Copy link

Can you suggest lower price alternative per request?

Im also looking for an alternative

@prasanna1780
Copy link

Please write to prasanna@pichainlabs.com : we have rc api at a competitive price

@ak4zh
Copy link

ak4zh commented Feb 1, 2023

I have built a vehicle api for my personal use case using multiple sources.
You can test at https://t.me/VehicleDetailsBot

(sharing as a telegram bot and not an api to keep it free and prevent from abuse)
Some values are obfuscated but can be made available.

@prathams96
Copy link

has anyone figured out a new source for this?

@ZOROsrk
Copy link

ZOROsrk commented Feb 25, 2024

Came across this RC API on Rapid Api, it contains more than 200 fields in the Response and is not expensive as well. After a lot of RnD this seems to be the only RC API that gives real time data and covers all most all the data at a reasonable price.

https://rapidapi.com/aitanlabs0/api/rto-vehicle-information-verification-india

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment