我正在從一個網站上抓取一些段落,我出現了這個問題,但我不知道如何解決它。
結構是這樣的,例如:
<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.
}
uj5u.com熱心網友回復:
調整選擇器以匹配p
標簽,然后遍歷每個標簽并構建您的資料。
試試這個:
// select p tags in the container
$('.container p', html).each(function(){
const text = $(this).text();
data.push({
text
});
});
console.log(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401174.html
標籤:javascript 查询 网页抓取 啦啦队
上一篇:函式回傳“無”Python
下一篇:抓取網路足球資料