code, the picture can be downloaded, but can not be opened, ask the gods to help
https://data.countryflags.com.
the first page to find the download URL. Find the picture link from the second page to download
var http = require("https");
var fs = require("fs");
var cheerio = require("cheerio");
var request = require("request");
var i = 0;
var q = 0;
var url = "https://data.countryflags.com/products/en/category/2996352/tiles/population-desc.html";
//url
function fetchPage(x) { //
startRequest(x);
}
//
function startRequest(x) {
//httpget
http.get(x, function (res) {
var html = ""; //html
var titles = [];
res.setEncoding("utf-8"); //
//data
res.on("data", function (chunk) {
html += chunk;
// console.log(html)
});
//endhtml
res.on("end", function () {
var $ = cheerio.load(html); //cheeriohtml
var link = "https:" + $("div.thumbnail a.clearfix").attr("href")
secondRequest(link)
});
}).on("error", function (err) {
console.log(err);
});
}
//
function secondRequest(link){
http.get(link, function (res) {
var html = ""; //html
var titles = [];
res.setEncoding("utf-8"); //
//data
res.on("data", function (chunk) {
html += chunk;
// console.log(html)
});
//endhtml
res.on("end", function () {
var $ = cheerio.load(html); //cheeriohtml
var news_item = {
//
title: $("div.panel-heading h3.panel-title").eq(0).text().trim(),
//url small png
link: "https:" + $("table.table-btn-spacing tbody tr").eq(1).children("td").eq(0).find("a").attr("href"),
//i
q: q = q + 1,
};
savedImg($,news_item); //
});
}).on("error", function (err) {
console.log(err);
});
}
//:
function savedImg($,news_item) {
var img_filename = news_item.title + ".png";
var img_src = news_item.link; //url
var options = {
url: img_src,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
}
};
//request
request.head(options,function(err,res,body){
if(err){
console.log(err);
}
});
request(options).pipe(fs.createWriteStream("./image/"+ img_filename)); ///image
// request("https://img.codeshelper.com/upload/img/2021/03/02/qpjohj3ojrc2262.com").pipe(fs.createWriteStream("./image/"+ img_filename));
}
fetchPage(url); //