Javascript 获取div web抓取中的属性
我想用cheerio来展示一个体育网站。我需要的其中一件事是从这一行获得数据gameidJavascript 获取div web抓取中的属性,javascript,node.js,cheerio,Javascript,Node.js,Cheerio,我想用cheerio来展示一个体育网站。我需要的其中一件事是从这一行获得数据gameid <div class="component game scoreboard-game margin-24-bottom epl full time margin-24-bottom" data-gameid="2146609" data-league="epl" data-show-date="" data-extra-class="margin-24-bottom" data-viewport-w
<div class="component game scoreboard-game margin-24-bottom epl full time margin-24-bottom" data-gameid="2146609" data-league="epl" data-show-date="" data-extra-class="margin-24-bottom" data-viewport-width="">
我真的搞不懂如何获取游戏ID号的数据。我知道这是一个简短的问题,但我不知道还需要说些什么才能使它更具体如果您想从DOM树中获取它,只需使用.attr方法即可 const gameId=$'.game'.attr'data-gameId'; 如果要从该字符串中提取它,请执行以下操作 常量nodeStr=`; const gameId=/data gameId=\d+/mgi.execnodeStr[1];//2146609 使用jQuery的方法如下:
$(".game").data("gameid");
或使用:
或者对于纯JavaScript解决方案:
document.querySelector(".game").getAttribute("data-gameid");
游戏[data gameid]不是更适合作为CSS选择器吗?然后,您可以确保,如果您确实使用game类返回了一个元素,那么它也将具有gameid数据属性,从而防止未定义该属性的任何问题。
document.querySelector(".game").getAttribute("data-gameid");