3

我是第一次使用 X 射线模块。

我使用它没有问题,但是当我尝试以格式错误的 HTML 代码抓取数据时遇到了一些问题。

例如,如果我尝试从网站上抓取此 HTML 代码:

<div class="item">
<dl class="list">
    <dd id="1"> Data1
    <dd id="2"> Data2
    <dd id="3"> Data3
</dl>

使用此代码:

x(html, '.item', [{
    tags: x('.item', 'dd:nth-child(1)')
}])
(function(err, obj) {
    var jsonCleaned = JSON.parse(JSON.stringify(obj).replace(/"\s+|\s+"/g,'"').replace(/\\n/g, ''))
    res.json(jsonCleaned);
})

我得到以下结果:

[
      {
                "tags": "Data1 Data2 Data3"
      }

]

如果 DD 标签被关闭,我的抓取代码就可以工作。

[
      {
                "tags": "Data1"
      }
]

有关如何解决此问题的任何解决方案?

4

1 回答 1

0

如果将来有人遇到同样的问题,这是我自己的解决方案。

我只是使用 htmltidy 模块。

tidy(html, function (err, html) {
    x(html, '.item', [{
        tags: x('.item', 'dd:nth-child(1)')
    }])
    (function(err, obj) {
        var jsonCleaned = JSON.parse(JSON.stringify(obj).replace(/"\s+|\s+"/g,'"').replace(/\\n/g, ''));
        res.json(jsonCleaned);
    })
});

之后,HTML 代码格式错误不再是问题。

于 2016-04-19T16:43:51.177 回答