console.log of undefined不记录

时间:2018-04-04 19:41:52

标签: javascript

我正在尝试使用此脚本从www.matchbook.com获取数据

function scrape(){
  var row = document.querySelectorAll(".mb-runner")[0]; //get rows
  console.log(row.textContent); //log row content
}setInterval(scrape, 1000);

此代码生成内联数据 ArsenalArsenal1.347 $ 2591.349 $ 20,8171.352 $ 4811.363 $ 11,2331.368 $ 11,4571.379 $ 9,948 没有分隔符。你知道我应该如何分离这些数据吗?

这里我发布了数据在网络上的显示方式 enter image description here

3 个答案:

答案 0 :(得分:0)

当该单元格的内容更改为MAKE OFFER时,它不再具有mb-price__odds类,因此选择器与下一个单元格匹配。

不要选择这个单元格的类,而是使用容器的类,我不认为它会消失。

然后在尝试访问.textContents之前检查这是否匹配。

function scrape() {
  var cell = document.querySelector(".mb-price:first-of-type .mb-price__odds");
  if (!cell) {
    console.log("Log me null please, do not skip to another cell !");
  } else {
    console.log(cell.textContents);
  }
}

答案 1 :(得分:0)

最后我通过这个javascript代码解决了我的问题:

function scrape(){
  var radek = document.querySelectorAll(".mb-runner")[2];//row
  var bunka = radek.querySelectorAll(".mb-price")[0]; //cell
  console.log(bunka.textContent); //cell value
}setInterval(scrape, 1000); //run every second

答案 2 :(得分:-1)

试试这个。

如果您只需要第一个元素

,则无需querySelectorAll

首先查找父级,并仅在元素存在时查找价格

对元素&&进行空值检查文字内容

function scrape(){
  var x = document.querySelector(".mb-price");
  var y = x && x.querySelector('.mb-price__odds');
  if (y && y.textContent){ 
    console.log(y.textContent);
  }
  else {
    console.log('No Content');
  }
}
相关问题