简体   繁体   English

如何在 Cheerio 中换行 p 标签?

[英]How can I line break p tag in Cheerio?

I'm scraping some paragraphs from a website and I occur this problem but I don't know how to resolve it.我正在从网站上抓取一些段落,我遇到了这个问题,但我不知道如何解决它。

The structure is something like this, for example:结构是这样的,例如:

<div class = "container">
   <p> This is a long paragraph 1. </p>
   <p> This is a long paragraph 2. </p>
   <p> This is a long paragraph 3. </p>
   <p> This is a long paragrahp 4. </p>
</div>

So I had do something like this to get the text inside the example paragraph I've just mentioned.所以我做了这样的事情来获取我刚才提到的示例段落中的文本。

function scrapeData() {
    let data = []
    let url = `scraping-url`;
    axios(url)
    .then(response =>{
        const html = response.data
        const $ = cheerio.load(html, {xmlMode: true})

        $('.container', html).each(function(){
            const text = $(this).find('p').text()
            data.push({
              text
            })
            console.log(data)
        })

    }).catch(err => console.log(err))
}

But the result I get is {This is a long paragraph 1.This is a long paragraph 2.This is a long paragraph 3.This is a long paragraph 4.} sticking together, I want to separate these paragraphs into each chunk of text但是我得到的结果是{This is a long paragraph 1.This is a long paragraph 2.This is a long paragraph 3.This is a long paragraph 4.}粘在一起,我想将这些段落分成每个文本块

I want it like this in my console.log(data)我希望在我的console.log(data)中像这样

{
    This is a long paragraph 1.
    This is a long paragraph 2.
    This is a long paragraph 3.
    This is a long paragraph 4.
}

Adapt the selector to match p tags, and then loop through each and construct your data.调整选择器以匹配p个标签,然后遍历每个标签并构造您的数据。

Try this:尝试这个:

   // select p tags in the container
    $('.container p', html).each(function(){
        const text = $(this).text();
        data.push({
          text
        });
    });

    console.log(data);

Maybe add the newlines after:也许在之后添加换行符:

$('p').after("\n")

Or when you join them:或者当你加入他们时:

$('p').get().map(p => $(p).text()).join("\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM