使用Axios发送多个HTTP请求

编程入门 行业动态 更新时间:2024-10-09 21:28:15

使用Axios发送<a href=https://www.elefans.com/category/jswz/34/1771377.html style=多个HTTP请求"/>

使用Axios发送多个HTTP请求

我正在尝试使用Node JS Axios爬网该网站以获得大学名称。我注意到该网站使用Paginated API,因此要检索所有我要发送多个请求的大学名称。

const url = ';_sortDirection=asc&study=Engineering&_mode=table&_page=1;
const url = ';_sortDirection=asc&study=Engineering&_mode=table&_page=2;
const url = ';_sortDirection=asc&study=Engineering&_mode=table&_page=3;
...
const url = ';_sortDirection=asc&study=Engineering&_mode=table&_page=55;

我已经编写了仅爬行一页的代码。我不知道如何抓取超过1页的内容。这是我的代码

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

_sort=rank&_sortDirection=asc&study=Engineering";
// table view
page= 1;
const url = ';_sortDirection=asc&study=Engineering&_mode=table&_page=' +page;

fetchData(url).then((res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const unilist = $('.TableTabular__TableContainer-febmbj-0.guaRKP > tbody > tr >td ');

    unilist.each(function() {

        let title = $(this).find('div').attr("name");

        if (typeof(title) == 'string') {
            console.log(title);
            fs.appendFileSync('universityRanking.txt', title+'\n', function (err) {
                if (err) return console.log(err);
              });

            } 

    });
})


async function fetchData(url){

    console.log("Crawling data...")

    // make http call to url
    let response = await axios(url).catch((err) => console.log(err));

    if(response.status !== 200){
        console.log("Error occurred while fetching data");
        return;
    }
    return response;

}

我希望获得55 Axios请求的帮助?我检查该页面有55页。我需要将每个页面的所有大学名称附加到文本文件中。

回答如下:

axios.all()方法可以帮助您解决用例。

axios.all([])   // Pass the array of axios requests for all the 55 pages here
  .then({
    // Multiple requests complete
  });

更多推荐

使用Axios发送多个HTTP请求

本文发布于:2024-05-07 10:02:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   Axios   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!