[英]How can I line break p tag in Cheerio?
我正在從網站上抓取一些段落,我遇到了這個問題,但我不知道如何解決它。
結構是這樣的,例如:
<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>
所以我做了這樣的事情來獲取我剛才提到的示例段落中的文本。
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))
}
但是我得到的結果是{This is a long paragraph 1.This is a long paragraph 2.This is a long paragraph 3.This is a long paragraph 4.}
粘在一起,我想將這些段落分成每個文本塊
我希望在我的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.
}
調整選擇器以匹配p
個標簽,然后遍歷每個標簽並構造您的數據。
嘗試這個:
// select p tags in the container
$('.container p', html).each(function(){
const text = $(this).text();
data.push({
text
});
});
console.log(data);
也許在之后添加換行符:
$('p').after("\n")
或者當你加入他們時:
$('p').get().map(p => $(p).text()).join("\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.