【问题标题】:Brake tags removed on x-ray scrape在 X 射线刮片上去除刹车标签
【发布时间】:2017-06-10 12:46:37
【问题描述】:

我是 JS 新手。我正在用 X 射线刮取一个网址。当按预期抓取标签时,标签会被删除,但我希望 <br> 标签被替换为 ;

例如: 如果我抓取类似'span#scraped-portion'

<span id="scraped-portion"><span class="bold>NodeJS</span><br>
    <span class="bold>Version:</span> 8<br><span class="bold>Date released:</span> 2017 Jan<br><span class="bold>Description:</span>Some other text
</span>

我会得到类似下面的结果

NodeJS /n Version: 8Date released: 2017 JanDescription: Some other text

&lt;br&gt; 标签周围的文字被加在一起,很难理解什么是什么。 所以我希望&lt;br&gt;标签被替换为;之类的东西。

有可能还是我应该更好地使用其他库?

【问题讨论】:

标签: javascript node.js web-scraping x-ray


【解决方案1】:

更新

我找到了一个纯基于 X-Ray 的解决方案,无需在使用 X-Ray 之前替换 html 中的 &lt;br&gt; 标签(请参阅下面的原始解决方案)。

这样,您将使用 X-Ray 的 filter 函数以及相互嵌入 X-Ray 函数(某种嵌套)。

首先,我们将使用为 X-Ray 定义的自定义过滤功能(称为 replaceLineBreak)替换原始 html 中的 &lt;br&gt; 标签。 其次,我们将使用替换的结果重建原始 html 结构(通过重新添加 &lt;span id="scraped-portion"&gt;)作为 X-Ray 调用的第一个参数。

希望你会喜欢!

    var x = Xray({
    filters: {
        replaceLineBreak: function (value) { return value.replace(/\<br\>/g, ';'); },
    }
});
var html =
`
    <span id="scraped-portion"><span class="bold">NodeJS</span><br>
        <span class="bold">Version:</span> 8<br><span class="bold">Date released:</span> 2017 Jan<br><span class="bold">Description:</span>Some other text
    </span>
`;

x(html,
    '#scraped-portion@html | replaceLineBreak' /// Filter function called to replace '<br>' to ';'
)(function (err, obj) {
    x(`<span id="scraped-portion">${obj}</span>`, /// Restore oroginal html structure to have the outer span with id 'scraped-portion
        '#scraped-portion'
    )(function (err2, obj2) { res.header("Content-Type", "text/html; charset=utf-8"); res.write(obj2); res.end(); })
    });

产生以下字符串:

NodeJS;   Version: 8;Date released: 2017 Jan;Description:Some other text

原始解决方案

为什么不在 X-Ray 处理 html 代码之前替换所有出现的 &lt;br&gt; 标签?

function tst(req, res) {
var x = Xray();
var html =
`
    <span id="scraped-portion"><span class="bold">NodeJS</span><br>
        <span class="bold">Version:</span> 8<br><span class="bold">Date released:</span> 2017 Jan<br><span class="bold">Description:</span>Some other text
    </span>
`.replace(/\<br\>/g, ';');

x
    (
    html,
    ['span#scraped-portion']
    )(function (err, obj) { res.header("Content-Type", "text/html; charset=utf-8"); res.write(JSON.stringify(obj, null, 4)); res.end(); })
    ;
}

那么你的代码会产生这样的结果

NodeJS;\n Version: 8;Date released: 2017 Jan;Description:Some other text\n

这几乎符合您的要求

【讨论】:

  • 非常感谢,我会尽快测试。现在我还有一个问题。如何创建 [{"Version": "8", "Date released": "2017 Jan", "Description" : "Some other text"}] 。我很快也会为此创建一个新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多