使用 cheerio 进行网页抓取:删除或忽略 child 元素?
Webscraping with cheerio: Deleting or ignoring a child element?
所以我有一个要抓取的网站,结构如下:
<p><strong>some headline:</strong> some content etc. blabla </p>
<p><strong>some other headline:</strong> some more content etc. blabla </p>
// and so on...
我用 cheerio 抓取如下:
$('p strong').each(function(i, element){
console.log($(this).text());
//gets me the headline
console.log("Parent:" + $(this).parent().text());
//gets me the content, but unfortunately, also the headline again
});
目前,我只是记录所有内容,但稍后我想将标题和内容保存在单独的变量中。然而,由于标题(在 <strong>
标签中找到)也是 <p>
标签的一部分,我的第二个命令(打算只获取内容,没有标题,因为我已经抓住了that) 不仅获得了内容,还获得了标题。我怎样才能分离或删除 <strong>
标签中的所有内容,并将所有其余内容保存在 <p>
标签中,即仅保存内容?
删除标题元素可能最简单:
$('p strong').each(function(i, element){
var $this = $(this);
var headline = $this.text(); // Get headline text
var parent = $this.parent(); // Get parent
$this.remove(); // Remove headline element
var body = parent.text(); // Get body text
// ...
});
所以我有一个要抓取的网站,结构如下:
<p><strong>some headline:</strong> some content etc. blabla </p>
<p><strong>some other headline:</strong> some more content etc. blabla </p>
// and so on...
我用 cheerio 抓取如下:
$('p strong').each(function(i, element){
console.log($(this).text());
//gets me the headline
console.log("Parent:" + $(this).parent().text());
//gets me the content, but unfortunately, also the headline again
});
目前,我只是记录所有内容,但稍后我想将标题和内容保存在单独的变量中。然而,由于标题(在 <strong>
标签中找到)也是 <p>
标签的一部分,我的第二个命令(打算只获取内容,没有标题,因为我已经抓住了that) 不仅获得了内容,还获得了标题。我怎样才能分离或删除 <strong>
标签中的所有内容,并将所有其余内容保存在 <p>
标签中,即仅保存内容?
删除标题元素可能最简单:
$('p strong').each(function(i, element){
var $this = $(this);
var headline = $this.text(); // Get headline text
var parent = $this.parent(); // Get parent
$this.remove(); // Remove headline element
var body = parent.text(); // Get body text
// ...
});