[英]Web scraping between two tags, using cheerio
各位晚上好,
我研究 cheerio 並嘗試解析該站點的數據。 它的結構如下,我將 go 直接上正文:
<body>
<form>
<div class="a">
<h3>Text A</h3>
<h4> Sub-Text A</h4>
<div class="Sub-Class A"> some text </div>
<h4> Sub-Text B</h4>
<div class="Sub-Class B"> some text </div>
<h4> Sub-Text C</h4>
<div class="Sub-Class C"> some text </div>
<h3>Text B</h3>
...
...
<h3>Text C</h3>
</div>
</form>
</body>
任務是將數據解析到數組中,從h3到下一個h3(即h3,所有h4和它后面的div,但到下一個h3)。 我開始寫一個function,但是遇到了上面描述的問題。 如何讓 function 明白我需要在數組的一個元素中的 h3 之后,但在下一個 h3 之前寫下所有內容?
我現在擁有的代碼:
const Nightmare = require('nightmare');
const cheerio = require('cheerio');
const nightmare = Nightmare({show: true})
nightmare
.goto(url)
.wait('body')
.evaluate(()=> document.querySelector('body').innerHTML)
.end()
.then(response =>{
console.log(getData(response));
}).catch(err=>{
console.log(err);
});
let getData = html => {
data = [];
const $ = cheerio.load(html);
$('form div.a').each((i, elem)=>{
data.push({
});
});
return data;
}
您可以僅跟隨“ next()”元素,直到找到h3:
let texts = $('h3').map((i, el) => {
let text = ""
el = $(el)
while(el = el.next()){
if(el.length === 0 || el.prop('tagName') === 'H3') break
text += el.text() + "\n"
}
return text
}).get()
我至少看到了幾種方法,具體取決於您想要什么。
也許你想要 select 一個<h3>
,比如第一個,然后遍歷到它之后的<h3>
,收集所有元素並忽略所有其他<h3>
標簽:
const $ = cheerio.load(html);
const text = $("h3")
.first()
.nextUntil("h3")
.map((i, e) => $(e).text())
.toArray();
console.log(text);
這給出:
[
' Sub-Text A',
' some text ',
' Sub-Text B',
' some text ',
' Sub-Text C',
' some text '
]
如果您願意,這些可以很容易地連接起來。
另一種解釋是您希望將所有<h2>
段分塊到單獨的子數組中:
const cheerio = require("cheerio"); // 1.0.0-rc.12
const html = `<body>
<form>
<div class="a">
<h3>Text A</h3>
<h4> Sub-Text A</h4>
<div class="Sub-Class A"> some text </div>
<h4> Sub-Text B</h4>
<div class="Sub-Class B"> some text </div>
<h4> Sub-Text C</h4>
<div class="Sub-Class C"> some text </div>
<h3>Text B</h3>
<h4> B STUFF</h4>
<div class="Sub-Class D"> B STUFF </div>
<h3>Text C</h3>
<div>C STUFF</div>
</div>
</form>
</body>`;
const $ = cheerio.load(html);
const groups = [...$("h3")]
.map(e => [...$(e).nextUntil("h3")].map(e => $(e).text()));
console.log(groups);
這給
[
[
' Sub-Text A',
' some text ',
' Sub-Text B',
' some text ',
' Sub-Text C',
' some text '
],
[ ' B STUFF', ' B STUFF ' ],
[ 'C STUFF' ]
]
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.