【问题标题】:Retrieving text from within div using node.js使用 node.js 从 div 中检索文本
【发布时间】:2015-11-09 20:37:17
【问题描述】:

我目前正在尝试编写一个刮板,它将使用 node.js 从 facebook 帖子中的 div 中获取所有“p”标签

页面上的每个帖子都位于所有具有此类的 div 中:.text_exposed_root

有时每个帖子中都有多个“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 .value 和 .html 但它们都只返回一个空白响应。我猜我可能需要抓取该 div 中的所有“p”标签并将其转换为字符串?

提前致谢。

已编辑:

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);
    }
})

【问题讨论】:

    标签: node.js request cheerio


    【解决方案1】:

    首先,您需要在请求中设置一些标头。没有它们,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 不会解析评论节点,因此您很可能需要删除 &lt;!----&gt; 并将结果加载回 Cheerio 以解析您想要的 html 部分。祝你好运!

    【讨论】:

    • 谢谢乔丹。我添加了一个正则表达式来删除 cmets 并试图将其传回,但 console.log(post) 是空白的?使用新代码编辑原始帖子。
    • @Paul'Macca'McGill 您的问题是您的常规 exp 删除了整个评论。我们只想删除评论标签,但保留其中的内容(这是您正在搜索的 html 所在的位置)。在上面找到我编辑的答案。它应该是你需要的。
    • 感谢您的帮助。我现在已经返回结果,但是我的 jquery 选择器似乎不起作用。我想选择其中包含的文本仅包含某些单词的第一类,然后获取其中的所有 p。 'console.log($('.text_exposed_root:first-child p').text()); ' 这将返回我第一个帖子,但随后帖子中的所有 p 标签也会返回。也尝试了以下,但它只是返回空白。 'console.log($('.text_exposed_root:first-child:contains("£25 - 1K Challenge -") p').text());'
    • 阅读cheerio github.com/cheeriojs/cheerio#each-functionindex-element- 的文档。有一个函数 .each() 可以帮助您遍历每个匹配的元素。然后你可以将文本存储在数组或其他东西中。该文档提供的示例可能与您要查找的内容非常接近。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2020-04-07
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多