2017-09-29 144 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某種原因使(用大口只是用於測試目的):

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標籤,但我認爲這並不總是在文本的末尾。

您也可以測試對一個空字符串翼:

if (el.textContent.trim() !== "") {} // you may want to trim() that for spaces