gpt4 book ai didi

python - 如何取消缩短 URL?

转载 作者:太空狗 更新时间:2023-10-29 16:58:41 25 4
gpt4 key购买 nike

我希望能够采用缩短或未缩短的 URL 并返回其未缩短的形式。我怎样才能编写一个 python 程序来执行此操作?

补充说明:

  • 情况 1:缩短 --> 未缩短
  • 情况 2:未缩短 --> 未缩短

例如输入数组中的 bit.ly/silly 应该是输出数组中的 google.com
例如输入数组中的 google.com 应该是输出数组中的 google.com

最佳答案

向 URL 发送 HTTP HEAD 请求并查看响应代码。如果代码是 30x,请查看 Location header 以获取未缩短的 URL。否则,如果代码是 20x,则不重定向 URL;您可能还想以某种方式处理错误代码(4xx 和 5xx)。例如:

# This is for Py2k.  For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse

def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
h.request('HEAD', parsed.path)
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return response.getheader('Location')
else:
return url

关于python - 如何取消缩短 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com