首页 > 解决方案 > 如何在 Cheerio 中执行索引以进行网页抓取

问题描述

我正在使用 Cheerio 进行网页抓取,我之前使用过 bs4。

我想抓取https://rera.kerala.gov.in/rera_project_details这个网站;在 Python 中刮表,我们可以使用 findall("tr")[0] 来获取 first <tr>

但是如何在 Cheerio 中执行相同的操作?

下面是我的代码:

var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');


const url = "https://rera.kerala.gov.in/rera_project_details";

const arr = [];
request({method:"GET",url}, function(err, res, body){
if (res.statusCode==200){

    let $  = cheerio.load(body);
    const getID = $("#block-zircon-content");
    const tbody = getID.find('tbody');
    tbody.each((i, el)=>{
    const ff = $(el).find("tr");
    console.log(ff.html());//it returns first tr
    //how to get 2 tr so that i can get td of second tr and can inde on td also
    })
    

}}
)

如果我遍历它返回所有 tr ,现在如何索引每个 td 以便在表的最后一列中我可以获得获取 pdf 的链接?

编辑

我已经到了这里,但是如何获取 tr 中的 td 元素列表:

    const getID = $(".views-table");
    
    const getBody = getID.find("tbody");
    
    const gettr = getBody.find("tr");
    const getfirsttr = $.html(gettr[0]);//it gives me first tr
    const getfirsttd = getfirsttr.find("td")//does not work

标签: javascriptnode.jsweb-scrapingcheerio

解决方案


要回答索引问题:

$('tr').eq(n)

会给你第n个tr作为cheerio对象。和

$('tr')[n]

将其作为 parse5 对象


推荐阅读