2017-09-29 11 views
0

記事から説明を取得するためにjsdomを使用しようとしています。 記事のhtmlコードはここjsdomイメージなしでテキストを取得

<p><img src="http://localhost/bibi_cms/cms/app/images/upload_photo/1506653694941.png" 
style="width: 599.783px; height: 1066px;"></p> 
<p>testestestestestestestest<br></p> 

は、コンテンツから説明を取得するための私のnodejsコードされているで、最初のpタグからテキストを取得し、空の文字列を出力しますようです。だから私はちょうど画像を含んでいないpタグの内容を取得したい。誰でもこの問題について私を助けてくれますか?

const dom = new JSDOM(results[i].content.toString()); 
if (dom.window.document.querySelector("p") !== null) 
results[i].description = dom.window.document.querySelector("p").textContent; 

答えて

1

理想的には、Node.TEXT_NODEに対してテストすることができますが、それは(単なるテスト目的のために一口を使用して)ので、いくつかの理由でnodejsに私のためerroringさ:

const gulp = require("gulp"); 
const fs = require('fs'); 

const jsdom = require("jsdom"); 
const { JSDOM } = jsdom; 

const html = yourHTML.html'; 

gulp.task('default', ['getText']); 

gulp.task('getText', function() { 

    var dirty; 
    dirty = fs.readFileSync(html, 'utf8'); 

    const dom = new JSDOM(dirty); 
    const pList = dom.window.document.querySelectorAll("p"); 

    pList.forEach(function (el, index, list) { 

    console.log("p.firstElementChild.nodeName : " + el.firstElementChild.nodeName); 

    if (el.firstElementChild.nodeName !== "IMG") { 
     console.log(el.textContent); 
    } 
}); 

return; 
}) 

ので、キーはテスト

です
el.firstElementChild.nodeName !== "IMG" 

imgタグまたはテキストのいずれかがpタグの後にあることがわかっている場合は、あなたの場合、firstElementChild.nodeNameは実際にはbrタグですが、必ずしもテキストの最後に必ずしもあるとは限りません。

あなたはまた、ALA、空の文字列に対してテストできます

if (el.textContent.trim() !== "") {} // you may want to trim() that for spaces 
関連する問題