Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save prolongservices/3078938c9cd56e6c5881ec1ca8a8b891 to your computer and use it in GitHub Desktop.

Select an option

Save prolongservices/3078938c9cd56e6c5881ec1ca8a8b891 to your computer and use it in GitHub Desktop.
Get vehicle info from an Indian registration number

PYTHON

Programmatically extract owner info from Indian registration numbers

Usage

$ python owner.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

PHP

...

Usage : http://yourwebsite/indiartoapi.php?reg1=KA05P&reg2=5175 ....

JAVA / Android

... getData(String str); You may have to call from background process since its a html api call. ...

import sys
import re
import requests
from bs4 import BeautifulSoup, SoupStrainer
home_url = 'https://parivahan.gov.in/rcdlstatus/?pur_cd=102'
post_url = 'https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml'
first = sys.argv[1]
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']
#print soup.findAll('button', id=re.compile('form_rcdl^'))
#print soup.findAll('button', id=lambda x: x and x.startswith('form_rcdl'))
i = 0
for match in soup.find_all('button', id=re.compile("form_rcdl")):
if i == 0:
button_id= match.get('id')
i = 1
data = {
'javax.faces.partial.ajax':'true',
'javax.faces.source':button_id,
'javax.faces.partial.execute':'@ALL',
'javax.faces.partial.render': 'form_rcdl:pnl_show form_rcdl:pg_show form_rcdl:rcdl_pnl',
button_id:button_id,
'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())
<?php
#Author : Srinath Rao
#Reason : No particular reason
#Usage : http://yourwebsite.com/rtoapi.php?reg1=KA05P&reg2=5175
#define constants
$home_url='https://parivahan.gov.in/rcdlstatus/?pur_cd=102';
$posturl = "https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml";
#get parameters from from URL
$reg1 = $_GET["reg1"];
$reg2 = $_GET["reg2"];
function scrape_out_nimmajji($html_data_out2, $find)
{
$lines = explode("\n", $html_data_out2);
$line_number = 0;
foreach ($lines as $num => $line) {
if (strpos($line, $find)) {
return strip_tags($lines[$line_number + 1]);
} else {
$line_number += 1;
}
}
return 0;
}
$ch = curl_init($home_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$jsessionid = trim($cookies["JSESSIONID"]) ;
$dom = new DOMDocument("1.0", "utf-8");
$dom->strictErrorChecking = false;
$dom->recover=true;
$dom->loadHTML($result);
$dom->preserveWhiteSpace = false;
$input_tags = $dom->getElementsByTagName('input');
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
$viewstate=$post_data["javax.faces.ViewState"];
$buttons = $dom->getElementsByTagName('button');
$i=0;
foreach($buttons as $button) {
$id = $button->getAttribute('id');
if ($i==1){
$first_left_button_id=$id;
}
$i=$i+1;
}
$header_value_array=array(
'Content-Type: application/x-www-form-urlencoded',
'Host: parivahan.gov.in',
'Accept: application/xml, text/xml, */*; q=0.01',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate, br',
'X-Requested-With: XMLHttpRequest',
'Faces-Request: partial/ajax',
'Origin: https://parivahan.gov.in',
'Cookie: JSESSIONID='.$jsessionid
);
$postdata = http_build_query(
array(
'javax.faces.partial.ajax' => 'true',
'javax.faces.source' => $first_left_button_id,
'javax.faces.partial.execute' => '@all',
'javax.faces.partial.render' => 'form_rcdl:pnl_show form_rcdl:pg_show form_rcdl:rcdl_pnl',
$first_left_button_id => $first_left_button_id,
'form_rcdl' =>'form_rcdl',
'form_rcdl:tf_reg_no1' => $reg1,
'form_rcdl:tf_reg_no2' => $reg2,
'javax.faces.ViewState' => $viewstate
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $header_value_array,
'content' => $postdata
)
);
$context = stream_context_create($opts);
$final_result = file_get_contents($posturl, false, $context);
$reg_no= trim(scrape_out_nimmajji($final_result, "Registration No:"));
$reg_date= trim(scrape_out_nimmajji($final_result, "Registration Date:"));
$chassis= trim(scrape_out_nimmajji($final_result, "Chassis No:"));
$engineno =trim(scrape_out_nimmajji($final_result, "Engine No:"));
$ownername=trim(scrape_out_nimmajji($final_result, "Owner Name:"));
$vehicleclass=trim(scrape_out_nimmajji($final_result, "Vehicle Class:"));
$fueltype=trim(scrape_out_nimmajji($final_result, "Fuel Type:"));
$fitnessupto=trim(scrape_out_nimmajji($final_result, "Fitness Upto:"));
$insuranceupto=trim(scrape_out_nimmajji($final_result, "Insurance Upto:"));
$fuelnorms=trim(scrape_out_nimmajji($final_result, "Fuel Norms:"));
$roadtaxpaidupto=trim(scrape_out_nimmajji($final_result, "Road Tax Paid Upto:"));
$return_data = array(
'vehicle_registration_info' => array(
'regno' => $reg_no,
'reg_date' => $reg_date,
'chassis' => $chassis,
'engineno' => $engineno,
'ownername' => $ownername,
'vehicleclass' => $vehicleclass,
'fueltype' => $fueltype,
'fitnessupto' => $fitnessupto,
'insuranceupto' => $insuranceupto,
'fuelnorms' => $fuelnorms,
'roadtaxpaidupto' => $roadtaxpaidupto,
)
);
echo json_encode($return_data);
?>
public class GetDataAsync extends AsyncTask<String, Void, String> {
private static int count = -1;
private final Activity activity;
private ProgressDialog dialog;
private final String reg1;
private final String reg2;
private final String reg3;
private final String reg4;
private String result = "";
public GetDataAsync(Activity activity, String str, String str2, String str3, String str4) {
this.activity = activity;
this.reg1 = str;
this.reg2 = str2;
this.reg3 = str3;
this.reg4 = str4;
}
/* Access modifiers changed, original: protected */
public void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(this.activity);
this.dialog.setMessage("Getting Data Wait...");
this.dialog.setCancelable(false);
this.dialog.show();
}
/* Access modifiers changed, original: protected|varargs */
public String doInBackground(String... strArr) {
try {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(this.reg1);
stringBuilder.append(this.reg2);
stringBuilder.append(this.reg3);
stringBuilder.append(this.reg4);
MainActivity.dataModel = getData(stringBuilder.toString());
this.result = "success";
} catch (Exception e) {
this.result = "";
e.printStackTrace();
}
return this.result;
}
/* Access modifiers changed, original: protected */
public void onPostExecute(String str) {
super.onPostExecute(str);
if (str.trim().length() <= 0) {
this.dialog.dismiss();
setNotify(this.activity, "Server Down Find information Using Send Sms.");
} else if (MainActivity.dataModel != null && MainActivity.dataModel.size() > 1) {
this.dialog.dismiss();
this.activity.startActivity(new Intent(this.activity, DetailActivity.class));
} else if (MainActivity.dataModel == null || MainActivity.dataModel.size() != 1) {
this.dialog.dismiss();
setNotify(this.activity, "Server down Please Find Information using send sms");
} else {
this.dialog.dismiss();
Toast.makeText(this.activity, "Search Again", 0).show();
}
}
public void setNotify(Activity activity, String str) {
new Builder(activity).setTitle("Alert").setMessage(str).setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
public static ArrayList getData(String str) {
ArrayList arrayList = new ArrayList();
ArrayList arrayList2 = new ArrayList();
String str2 = "";
Matcher matcher = Pattern.compile("(\\w{2})(\\d{2})(\\D*?)(\\d{1,4})").matcher(str);
if (matcher.matches()) {
str2 = matcher.replaceFirst("$1$2$3-$4");
}
String[] split = str2.split("-");
String str3 = split[0];
str = split[1];
try {
Response execute = Jsoup.connect("https://parivahan.gov.in/rcdlstatus/?pur_cd=102").validateTLSCertificates(false).followRedirects(true).ignoreHttpErrors(true).method(Method.GET).execute();
if (execute.statusCode() <= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
Map cookies = execute.cookies();
Document parse = Jsoup.parse(execute.body());
Element first = parse.getElementsByAttributeValue("name", "javax.faces.ViewState").first();
if (first == null) {
first = parse.getElementById("j_id1:javax.faces.ViewState:0");
}
String attr = first.attr("value");
String trim = ((Element) Jsoup.parse(execute.body()).getElementsByAttributeValueStarting("id", "form_rcdl:j_idt").select("button").get(0)).attr("id").trim();
str = Jsoup.connect("https://parivahan.gov.in/rcdlstatus/vahan/rcDlHome.xhtml").validateTLSCertificates(false).followRedirects(true).method(Method.POST).cookies(cookies).referrer("https://parivahan.gov.in/rcdlstatus/?pur_cd=102").header("Content-Type", URLEncodedUtils.CONTENT_TYPE).header("Host", "parivahan.gov.in").header(HttpHeaders.ACCEPT, "application/xml, text/xml, */*; q=0.01").header(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5").header(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br").header("X-Requested-With", "XMLHttpRequest").header("Faces-Request", "partial/ajax").header("Origin", "https://parivahan.gov.in").userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36").data("javax.faces.partial.ajax", "true").data("javax.faces.source", trim).data("javax.faces.partial.execute", "@all").data("javax.faces.partial.render", "form_rcdl:pnl_show form_rcdl:pg_show form_rcdl:rcdl_pnl").data(trim, trim).data("form_rcdl", "form_rcdl").data("form_rcdl:tf_reg_no1", str3).data("form_rcdl:tf_reg_no2", str).data("javax.faces.ViewState", attr).execute().body();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("str2 ");
stringBuilder.append(str);
if (str.contains("Registration No. does not exist!!!")) {
arrayList2.add(0, "No Record(s) Found");
} else {
stringBuilder = new StringBuilder();
stringBuilder.append("<!DOCTYPE html><html><body>");
stringBuilder.append(str.substring(str.indexOf("<table"), str.lastIndexOf("</table>")));
stringBuilder.append("</body></html>");
Document parse2 = Jsoup.parse(stringBuilder.toString());
int indexOf = str.indexOf("<div class=\"font-bold top-space bottom-space text-capitalize\">") + 62;
str.substring(indexOf, str.indexOf("</div>", indexOf)).replaceAll("Registering Authority:", "").trim();
Element first2 = parse2.select("table").first();
if (first2 != null) {
Elements select = first2.select("tr");
for (int i = 0; i < select.size(); i++) {
Elements select2 = ((Element) select.get(i)).select("td");
for (int i2 = 0; i2 < select2.size(); i2++) {
String text = ((Element) select2.get(i2)).text();
Log.e("text", text);
if (!text.trim().equals("Owner Name:")) {
if (count != i2) {
arrayList.add(text);
}
}
if (count == -1) {
count = i2 + 1;
} else {
count = -1;
}
arrayList2.add(text);
}
}
arrayList2.addAll(arrayList);
} else {
arrayList2.add(0, "No Record(s) Found");
}
}
} else {
arrayList2.add(0, "500 Server Error");
}
} catch (Exception unused) {
arrayList2.add(0, "Server Error");
}
return arrayList2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment