gpt4 book ai didi

javascript - 如何使用 X 射线抓取格式错误的 HTML 代码

转载 作者:搜寻专家 更新时间:2023-11-01 00:06:26 24 4
gpt4 key购买 nike

我是第一次使用 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"
}
]

关于如何解决这个问题的任何解决方案?

最佳答案

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

我只使用 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 代码不再是问题。

关于javascript - 如何使用 X 射线抓取格式错误的 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com