我希望能够获取缩短或未缩短的URL并返回其未缩短的表单.我怎么能做一个python程序来做到这一点?
额外澄清:
例如bit.ly/silly,在输入数组中应该google.com在输出数组中,
例如google.com在输入数组中应该google.com在输出数组中
当最终的网址是https时,我希望在python中取消(解析)一个网址.我看到了一个问题:如何使用python取消缩短URL? (以及类似的其他人),但正如对已接受答案的评论中所述,此解决方案仅在网址未重定向到https时有效.
作为参考,该问题中的代码(在重定向到http url时工作正常)是:
# 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)
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
h.request('HEAD', resource )
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return unshorten_url(response.getheader('Location')) # changed to process chains of short urls
else:
return url
Run Code Online (Sandbox Code Playgroud)
(注意 - 出于明显的带宽原因,我希望通过仅询问文件头[即像上面的http-only版本]而不是通过询问整个页面的内容来实现)