【问题标题】:x-ray: Read HTML <div> attributesx-ray:读取 HTML <div> 属性
【发布时间】:2017-07-19 07:53:45
【问题描述】:

我正在编写一个开源包,它读取带有城市自行车可用性状态的 HTML,并将数据转换为通过 API 提供的 JSON。

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'>
    ...

代码

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]);
});

结果

请注意,lat 不见了 -

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

我的问题

我已经设法使用.title.address 获取divs 的内容,但我没有设法获取属性,例如data-latdata-id.

如何使用 X 射线读取 div 属性?

【问题讨论】:

    标签: html properties x-ray


    【解决方案1】:

    @ 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]);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 2017-11-23
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多