很抱歉,如果之前已经解决过这个问题,但我找不到任何先前的解决方案。我正在使用 Pandas 从 URL 中提取域并计算结果。有没有办法根据 URL 是否是短链接(例如 bit.ly 和 goo.gl)来分配 bool 值? urllib.urlopen 可以用来验证链接是否是短链接吗?
这是伪Python,希望能够说明我正在尝试做的事情:
if urllib.urlopen(df['url']) != df['url']:
df['short_url'] = True
else:
df['short_url'] = False
最佳答案
本质上,“短网址”是一个仅重定向到最终网址的外观网址。因此您可以使用 urllib2 中的 getUrl 方法。
geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
import urllib2
original_url = 'http://someshorturl/5b2su2'
response = urllib2.urlopen(original_url)
# final_url != original_url if redirected
final_url = response.geturl()
# response_code will be 302 for redirects
response_code = response.getcode()
if response_code == 302:
# redirected so this may a short url
else:
# this is not a short url
当然,这有一个缺陷,因为任何 url 都可以是重定向...而不仅仅是来自 url 缩短服务(如 goo.gl 或tinyrl)的短 url。
如果您确实需要 100% 确定,那么您可能需要针对已知的 url 缩短服务域对 url 进行正则表达式测试。您可能需要组合执行多项操作才能满足您的要求。
关于python - 使用Python检测短网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219063/