x-ray: Read HTML <div> attributes

219 Views Asked by At

I am writing an open source package that reads an HTML with city bike availability status and converts the data to a JSON served via an API.

HTML

    <div id="gmap"><div class='marker' data-lat='32.096100' data-lng='34.821400' data-name='דרך בן גוריון 2 פינת אבא הלל - רמת-גן' data-id='652'>
        <div class='marker-popover' data-lat='32.096100' data-lng='34.821400'>
            <div class='title'>דרך בן גוריון 2 פינת אבא הלל - רמת-גן (652)</div>
            <div class='station-data'>
                <div class='address'>דרך בן גוריון 2 פינת אבא הלל - רמת-גן <a href='#' class='navi'>נווט לתחנה <i class='fa fa-location-arrow'></i></a></div>
                <span class='bikes'><i class='fa fa-bicycle'></i> אופניים זמינים: 9</span>
                <span><i class='fa fa-park'></i> עמודים פנויים: 1</span>
            </div>
            <!--<div class='nearby-stations'>
                <div class='subtitle'>תחנות קרובות</div>
                <ul></ul>
            </div>-->
        </div>
    </div><div class='marker' data-lat='32.099200' data-lng='34.825500' data-name='איצטדיון רמת-גן מול שער 16' data-id='651'>
    ...

Code

const path = require('path');
const Xray = require('x-ray');
const read = require('fs').readFileSync;

const html = read(path.resolve(__dirname, 'index.html'));
const xray = Xray();

// How to fetch the 'data-lat' property?
xray(html, '.marker', [{ bikes: '.bikes', title: '.title', lat: 'data-lat' }])((err, value) => {
  console.log(value[0]);
});

Results

Note that lat is missing -

{ bikes: ' אופניים זמינים: 9',
  title: 'דרך בן גוריון 2 פינת אבא הלל - רמת-גן (652)' }

My problem

I have managed to fetch the content of divs using .title and .address, but I didn't manage to fetch the attributes, like data-lat or data-id.

How can I read a div property using x-ray?

1

There are 1 best solutions below

0
On

@ did the trick:

const path = require('path');
const Xray = require('x-ray');
const read = require('fs').readFileSync;

const html = read(path.resolve(__dirname, 'index.html'));
const xray = Xray();

xray(html, '.marker', [
  {
    bikes: '.bikes',
    title: '.title',
    lat: '@data-lat' }, // <div class='marker' data-lat='32.096100' data-lng='34.821400' ...
])((err, value) => {
  console.log(value[0]);
});