And*_*rew 15 python url url-shortener
我希望能够获取缩短或未缩短的URL并返回其未缩短的表单.我怎么能做一个python程序来做到这一点?
额外澄清:
例如bit.ly/silly,在输入数组中应该google.com在输出数组中,
例如google.com在输入数组中应该google.com在输出数组中
Ada*_*eld 35
向URL发送HTTP HEAD请求并查看响应代码.如果代码是30x,请查看Location标题以获取未缩减的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
Run Code Online (Sandbox Code Playgroud)
Ger*_*inZ 22
使用请求:
import requests
session = requests.Session() # so connections are recycled
resp = session.head(url, allow_redirects=True)
print(resp.url)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Python 3.5+,您可以使用Unshortenit模块,这使这变得非常简单:
from unshortenit import UnshortenIt
unshortener = UnshortenIt()
uri = unshortener.unshorten('https://href.li/?https://example.com')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14788 次 |
| 最近记录: |