Jitendra Sharma Jitendra Sharma - 1 month ago 8
Java Question

Trying to scarp Dynamic data from web using Jsoup to android app,but not getting exact data

Below is my code. Please go to webpage that I am parsing. I want to extract "Delhi load" and "frequency". Using

substring
I get "delhi load" correctly but in case of Frequency I fail because the position of string changes sometimes. So as result I get following results:

50.05
or
50.0<


because sometime decimal value creates problem.

class parsepage extends AsyncTask<String,Void,String> {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView=(TextView) findViewById(R.id.txtload);
Log.d("test",parseddata);
textView.setText(parseddata);
}

@Override
protected String doInBackground(String... params) {
org.jsoup.nodes.Document doc;
try {
doc= Jsoup.connect("http://www.delhisldc.org/DynamicData.aspx").get();

Element element=doc.getElementById("LblLoad");
Element element1=doc.getElementById("LblFrequency");
Element element2=doc.getElementById("LblMaxToday");
delhiload=element.toString().substring(95,99);
delhifreq=element1.toString().substring(100,105);
delhimaxload=element2.toString().substring(99,104);
parseddata="Delhi Load:"+delhiload+System.getProperty ("line.separator")+"Frequency:"+delhifreq+System.getProperty ("line.separator")+"Max Load:"+delhimaxload;
}
catch (IOException e){
e.printStackTrace();
}

// this.publishProgress(parseddata);
return parseddata;
}
}

Answer

The text() method provides the functionality to grab the textnodes of a html element (see: https://jsoup.org/cookbook/extracting-data/attributes-text-html). Your selectors are already correct, just use text() instead of your substring tries.

Adjusted Code

try {
    doc=  Jsoup.connect("http://www.delhisldc.org/DynamicData.aspx").get(); 

    Element element=doc.getElementById("LblLoad");
    Element element1=doc.getElementById("LblFrequency");
    Element element2=doc.getElementById("LblMaxToday");

    delhiload = element.text();
    delhifreq = element1.text();
    delhimaxload = element2.text();

    parseddata="Delhi Load:"+delhiload+System.getProperty ("line.separator")+"Frequency:"+delhifreq+System.getProperty ("line.separator")+"Max Load:"+delhimaxload;

} catch (IOException e) {
    e.printStackTrace();
}

Output of parseddata

Delhi Load:5271
Frequency:50.1
Max Load:5442 at 22:50:40
Comments