使用 jquery 遍历 dom 来抓取数据

using jquery to traverse dom for scraping data

我正在使用节点 phantom simple https://github.com/baudehlo/node-phantom-simple。它使抓取 dom 变得非常简单。我被允许使用 jquery 并且我正在进入数据-table 库。

这是我开始使用的代码

 var nameArray = [];

        $("tbody[role='alert'] tr").each(function(data){
              var json = {};
              json.name= $(this).children(':first-child').text();
              json.size= $(this).children(':nth-child(2)').text();
              json.caffeine= $(this).children(':nth-child(3)').text();
              json.mgFloz=$(this).children(':last-child').text();
            nameArray.push(json);
        });

        // return tableData;
            return nameArray;

我将从我抓取的网站返回所有数据。每个 table 行的内部是格式

<td><a href="">name of drink</a></td>
<td>info</td>
<td>info</td>
<td> info</td>

我正在寻找饮料 href。所以我试图瞄准 html

json.url=$(this).children(':first-child').html();

我的回答是

{ url: '<a href="/caffeine-content/zombie-blood-energy-potion">Zombie Blood Energy Potion</a>' }

这很接近。我想要的只是 href,我会完成的。我尝试使用 attr() 进行定位,但我一直返回 null。

是否有我遗漏的步骤或解决方法?

你很接近了,但你需要再向下遍历DOM一层。使用 find():

json.url = $(this).children(':first-child').find('a').attr('href');

对于name属性,可以使用类似的方法:

json.name = $(this).children(':first-child').find('a').text();