从div内使用node.js检索文本

我目前正试图写一个刮板,将获得所有的'p'标签内的一个div内使用node.js

页面上的每个post都在div中,都有这个类:.text_exposed_root

有时在每个post内有多个“p”标签,所以如果可能的话,我需要抓取该div内的所有html文本。 我正在使用cheerio和请求模块,我的代码到目前为止如下:

request(BTTS, function(error, response, body){ if (!error){ var $ = cheerio.load(body), post = $(".text_exposed_root p").text(); console.log(post); } else { console.log("We've encountered an error: " + error); } }) 

我曾尝试使用.text。值和.html,但他们都只是返回一个空白的回应。 我猜我需要抓住所有的'P'标签内的该部分,并转换为string也许?

提前致谢。

编辑:

 var url = ('https://www.facebook.com/BothTeamsToScore'); request({url:url, headers: headers}, function(error, response, body){ if (!error){ var strippedBody = body.replace(/<!--[\s\S]*?-->/g, "") console.log(strippedBody); var $ = cheerio.load(strippedBody), post = $(".text_exposed_root p").text(); console.log(post); } else { console.log("We've encountered an error: " + error); } }) 

首先,你需要设置一些你的请求标题。 没有他们,Facebook会回应和“不受支持的浏览器”页面。 这是你的第一个问题。

 var headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36', 'Content-Type' : 'application/x-www-form-urlencoded' } var url = BTTS request({url:url, headers: headers}, function(error, response, body){ if (!error){ var $ = cheerio.load(body.replace(/<!--|-->/g, '')) console.log($('.text_exposed_root p').text()) } else { console.log("We've encountered an error: " + error); } }) 

另一件需要注意的是,内容来自html评论。 即

 <code class="hidden_elem"><!-- ... <div class="text_exposed_root"> <p>text</p> 

Cheerio不会parsing注释节点,所以你很可能需要删除<!---->并将结果加载回cheerio来parsing你想要的html部分。 祝你好运!