2017-09-29 10 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 태그이지만 텍스트의 끝 부분에 항상 반드시 있어야한다고 가정합니다.

또한 알라 빈 문자열에 대해 테스트 할 수 :

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