我正在练习通过使用 Cheerio 进行抓取来创建 API。我正在从这个相当复杂的网站上抓取:http://www.vegasinsider.com/nfl/odds/las-vegas/
我试图在这些之后定位文本<br>
锚标签内的标签<td>
元素:
<td class="viCellBg1 cellTextNorm cellBorderL1 center_text nowrap"
width="56">
<a class="cellTextNorm" href="/nfl/odds/las-vegas/line-movement/packers-@-
bears.cfm/date/9-05-19/time/2020#BT" target="_blank">
<br>46u-10<br>-3½ -10
</a>
</td>
下面的代码是我用来定位我想要的数据的代码。我遇到的问题是我不知道如何在之后获取该文本<br>
标签。我尝试过 .find('br') 但无法让它工作。这是代码:
app.get("/nfl", function(req, res) {
var results = [];
axios.get("http://www.vegasinsider.com/nfl/odds/las-vegas/").then(function(response) {
var $ = cheerio.load(response.data);
$('span.cellTextHot').each(function(i,element) {
// console.log($(element).text());
var newObj = {
time:$(element).text()
}
$(element).parent().children().each(function(i,thing){
if(i===2){
newObj.awayTeam = $(thing).text();
}
else if (i===4){
newObj.homeTeam = $(thing).text();
}
});
newObj.odds= $(element).parent().next().next().text().trim();
$('.frodds-data-tbl').find('td').next().next().children().each(function(o, oddsThing){
if(o===0){
newObj.oddsThing = $(oddsThing).html();
}
});
res.json(results);
});
});
您可以看到我能够将此框中的所有文本输出到 newObj.odds 值。我尝试使用类似下一行的内容,其中我定位 td 元素并循环并将每一行分解为自己的 newObj 属性,例如 newObj.oddsLine1 和 newObj.oddsLine2 。
希望这是有道理的。任何帮助是极大的赞赏。
您无法使用cheerio选择文本节点,您需要使用js dom属性/函数:
$('td a br')[0].nextSibling.nodeValue
注意 $(css)[0] 将为您提供第一个元素作为 js 对象(而不是 Cheerio 对象)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)