在 Python 中异步 URL 取消缩短

Asynchronous URL un-shortening in Python

我目前正在尝试在我的程序中实现一项功能,该功能将检测并取消缩短任何 URL 缩短器,包括 bit.ly 和旧的 goo.gl links(现在不复存在)。我已经找到了几篇文章,我将讨论我目前的实验、发现并提出 "Is there even a way to do it?"

的问题

我首先阅读了之前找到的所有文章。我发现了 Stack Overflow on how to un-shorten URLs using Python. The answer pointed to the requests library, using requests.head, setting allow_redirects to True. requests does not function with async.io at all. Which is where I found a question based on Async requests with Python requests (found here)

这个问题指向 grequests,这是请求的异步版本,但是,当我尝试使用第一个问题的代码时,将 requests 替换为 grequests,它做到了重定向后不显示 link 位置。然后我将 .head 更改为 .get,虽然它确实有效,但它仍然提供了我正在使用的 bit.ly URL,而不是未缩短的 URL.

我不确定在取消缩短后我可以使用什么来找到 URL 位置而不使其同步而不是异步。如果有人可以提供帮助,那将非常有用!

我推荐使用的一个很好的库是 aiohttp,一个允许异步 Web 请求的库。

试试这个,然后 运行 使用 .apply(lambda) 将其作为数据框的循环:

import requests

def unshortenurlx(url):
    try:
        response = requests.get(url)
        return(response.url)
    except Exception as e:
        return('Bad url {url}. {e}'.format(url=url, e=e))