I' trying to scrape a html page and make it into a json object
this is the page the page
<html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href="index.html">Index</a> ] | [ <a href="config.html">Device Config</a> ]</p></div><div>Neighbors<pre>fe80::212:4b00:8b8:6ecb REACHABLE</pre></div><div>Default Route<pre>fe80::212:4b00:8b8:6ecb</pre></div><div>Routes<pre></pre></div><div>Sensors<pre>Battery Temp = 19 C
Battery Volt = 3320 mV
Air Pressure = 1031.12 hPa
Air Temp = 22.66 C
Object Temp = 12.375 C
Ambient Temp = 23.062 C
Light = 0.00 lux
HDC Humidity = 43.93 %RH
HDC Temp = 23.03 C
Acc X = 0.02 G
Acc Y = 0.02 G
Acc Z = -1.10 G
Gyro X = -2.93 deg per sec
Gyro Y = -2.74 deg per sec
Gyro Z = 5.18 deg per sec</pre></div><div>Page hits: 4<br>Uptime: 138 secs<br></div></body></html>
This is my attempt :
var request = require('request');
var cheerio = require('cheerio');
request('http://[aaaa::212:4b00:c2a:b704]/index.html', function(error, response,html){
if(!error && response.statusCode == 200){
//JSON.parse(html)
//console.log('--------------------------------------');
var temp = {"id":html}
var obj = JSON.parse(temp)
console.log(JSON.stringify(obj));
}
});
how can I achieve putting the sensors div into an object that contain the sensors names as keys and the data of the sensors as proprieties
UPDATE :
thanks to Rafal Wiliński help I somehow managed to get it working but the last key is taking divs as a value in the object
new code :
var request = require('request');
var cheerio = require('cheerio');
request('http://[aaaa::212:4b00:c2a:b704]/index.html', function(error, response,html){
if(!error && response.statusCode == 200){
var obj = {};
html.split('\n').forEach((line) => {
var key = line.split(' = ')[0];
var value = line.split(' = ')[1];
obj[key] = value;
});
console.log(JSON.stringify(obj,null,' '))
}});
but my output is
{
"Battery Temp": "22 C",
"Battery Volt": "3320 mV",
"Air Pressure": "1031.36 hPa",
"Air Temp": "26.09 C",
"Object Temp": "15.531 C",
"Ambient Temp": "26.312 C",
"Light": "0.08 lux",
"HDC Humidity": "34.73 %RH",
"HDC Temp": "26.38 C",
"Acc X": "0.02 G",
"Acc Y": "0.00 G",
"Acc Z": "-1.05 G",
"Gyro X": "-2.11 deg per sec",
"Gyro Y": "-1.10 deg per sec",
"Gyro Z": "3.64 deg per sec</pre></div><div>Page hits: 18<br>Uptime: 2968 secs<br></div></body></html>"
}