有没有办法访问一个缩短的url并解析该url的扩展版本?R、 Python,JS/Node



例如,如果我访问像tripadvisor.com/6887990这样的url

出现在浏览器中的url的扩展版本变为https://www.tripadvisor.com.au/Attraction_Review-g1121284-d6887990-Reviews-Koishidani_Shrine-Minamiyamashiro_mura_Soraku_gun_Kyoto_Prefecture_Kinki.html

有没有一种方法可以通过编程访问缩短的URL的整个列表/向量/数组,然后将扩展的URL存储在另一个列表/向量或数组中?

很乐意使用任何可以实现这一点的语言,但最好使用R、Python或JS/Node

提前感谢!

在node.js中,您可以找到重定向的URL如下所示:

const got = require('got');
got('https://www.tripadvisor.com/6887990', {followRedirect: false}).then(r => {
if (r.statusCode === 301 || response.statusCode === 302) {
console.log(r.headers.location);    // this will be the redirect URL
} else {
console.log(`statusCode ${r.statusCode} was not a redirect`);
}
}).catch(err => {
console.log(err);
});

然后,您可以使用重定向后的URL来获取实际内容。或者,您可以让got()库自动为您执行重定向,并让它为您获取内容。

got('https://www.tripadvisor.com/6887990').then(r => {
console.log(r.body);            // this is the content of the redirected page
}).catch(err => {
console.log(err);
});

要运行一组URL,最安全的方法是一次运行一个(以避免速率限制或DOS限制(:

async function run(listOfUrls) {
let results = [];
for (let url of listOfUrls) {
let response = await got(url);
if (response.statusCode === 301 || response.statusCode === 302) {
results.push(response.headers.location);
} else {
results.push(url);
}            
}
return results;
}
run(["https://somedomain.com/url1", "https://somedomain.com/url2", ...])
.then(results => {
console.log(results);
})
.catch(err => {
console.log(err);
});