【问题标题】:Is there a way to visit a shortened url and parse the extended version of that url? R, Python, JS/Node [closed]有没有办法访问缩短的 url 并解析该 url 的扩展版本? R,Python,JS /节点[关闭]
【发布时间】:2020-11-12 15:40:11
【问题描述】:

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

出现在浏览器中的那个 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 中

提前致谢!

【问题讨论】:

  • @IainShelvington 我有一个预定义的有限网址列表。
  • @IainShelvington 这听起来是个好主意,我想要一个实际的例子来说明这是如何实现的。

标签: javascript python r node.js python-requests


【解决方案1】:

在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);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2016-08-03
    • 2018-12-09
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多