JavaScript GET 请求:带请求头、URL 递增及休眠
以下是一个可能的实现:
const https = require('https');
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
};
let weekId = 1924;
function makeRequest() {
const url = `https://example.com/api?weekId=${weekId}`;
const options = {
headers: headers,
method: 'GET',
timeout: 5000,
url: url
};
https.get(url, options, (res) => {
console.log(`Got response for weekId=${weekId}: ${res.statusCode}`);
// do something with the response, e.g. read the data
// and parse it as JSON if applicable
// increase the weekId and schedule the next request
weekId += 31;
if (weekId <= 2024) {
setTimeout(makeRequest, 10000);
}
}).on('error', (err) => {
console.error(`Error for weekId=${weekId}: ${err}`);
// schedule the next request regardless of error
weekId += 31;
if (weekId <= 2024) {
setTimeout(makeRequest, 10000);
}
});
}
// start the first request
makeRequest();
原文地址: https://www.cveoy.top/t/topic/ndkG 著作权归作者所有。请勿转载和采集!