我希望能够采用缩短或未缩短的 URL 并返回其未缩短的形式。我怎样才能制作一个python程序来做到这一点?
附加说明:
- 案例 1:缩短 --> 未缩短
- 情况 2:未缩短 --> 未缩短
例如bit.ly/silly
在输入数组中应该google.com
在输出数组中
例如google.com
在输入数组中应该google.com
在输出数组中
我希望能够采用缩短或未缩短的 URL 并返回其未缩短的形式。我怎样才能制作一个python程序来做到这一点?
附加说明:
例如bit.ly/silly
在输入数组中应该google.com
在输出数组中
例如google.com
在输入数组中应该google.com
在输出数组中
向 URL 发送 HTTP HEAD 请求并查看响应代码。如果代码是 30x,请查看Location
标头以获取未缩短的 URL。否则,如果code是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
使用请求:
import requests
session = requests.Session() # so connections are recycled
resp = session.head(url, allow_redirects=True)
print(resp.url)
Unshorten.me有一个 API,可让您发送 JSON 或 XML 请求并获取返回的完整 URL。
打开网址,看看它解析为:
>>> import urllib2
>>> a = urllib2.urlopen('http://bit.ly/cXEInp')
>>> print a.url
http://www.flickr.com/photos/26432908@N00/346615997/sizes/l/
>>> a = urllib2.urlopen('http://google.com')
>>> print a.url
http://www.google.com/
要取消简短,您可以使用请求。这是一个对我有用的简单解决方案。
import requests
url = "http://foo.com"
site = requests.get(url)
print(site.url)
如果您使用的是 Python 3.5+,您可以使用Unshortenit模块,这使得这非常容易:
from unshortenit import UnshortenIt
unshortener = UnshortenIt()
uri = unshortener.unshorten('https://href.li/?https://example.com')
http://github.com/stef/urlclean
sudo pip install urlclean
urlclean.unshorten(url)
这里的 src 代码几乎考虑了有用的极端情况:
src 代码在 github @ https://github.com/amirkrifa/UnShortenUrl
欢迎评论...
import logging
logging.basicConfig(level=logging.DEBUG)
TIMEOUT = 10
class UnShortenUrl:
def process(self, url, previous_url=None):
logging.info('Init url: %s'%url)
import urlparse
import httplib
try:
parsed = urlparse.urlparse(url)
if parsed.scheme == 'https':
h = httplib.HTTPSConnection(parsed.netloc, timeout=TIMEOUT)
else:
h = httplib.HTTPConnection(parsed.netloc, timeout=TIMEOUT)
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
try:
h.request('HEAD',
resource,
headers={'User-Agent': 'curl/7.38.0'}
}
)
response = h.getresponse()
except:
import traceback
traceback.print_exec()
return url
logging.info('Response status: %d'%response.status)
if response.status/100 == 3 and response.getheader('Location'):
red_url = response.getheader('Location')
logging.info('Red, previous: %s, %s'%(red_url, previous_url))
if red_url == previous_url:
return red_url
return self.process(red_url, previous_url=url)
else:
return url
except:
import traceback
traceback.print_exc()
return None
您可以使用geturl()
from urllib.request import urlopen
url = "bit.ly/silly"
unshortened_url = urlopen(url).geturl()
print(unshortened_url)
# google.com
这是非常简单的任务,您只需要添加 4 行代码即可:)
import requests
url = input('Enter url : ')
site = requests.get(url)
print(site.url)
只需运行此代码,您将成功取消短网址。