【问题标题】:Unshorten url in python 3在python 3中取消缩短网址
【发布时间】:2019-05-12 04:01:40
【问题描述】:

我在 python 3 中使用此代码来缩短 url,但代码返回原样(缩短)的 url,那么我应该怎么做才能使其不缩短?

import requests
import http.client
import urllib.parse as urlparse   

def unshortenurl(url):
    parsed = urlparse.urlparse(url) 
    h = http.client.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 python-3.x url urllib3 http.client


【解决方案1】:

在 python3 中,response.status/100 == 3 将是 True,仅用于状态代码 300。对于任何其他 3xx 代码,它将是 False。使用楼层除法 response.status//100 == 3 或其他方式来测试重定向代码。

编辑:看起来您正在使用来自SO question posted by @Aybars 的代码,并且在 sn-p 顶部有注释在 python3 中做什么。另外,最好能提及代码的来源。

【讨论】:

  • 试图将 response.status/100 == 3 改为 response.status//100 == 3 但没有解决问题
  • 查看原始SO问题代码顶部的注释
  • 感谢您的澄清,有没有办法检查网址是否缩短,以便我只取消缩短的网址以争取时间!
猜你喜欢
  • 2021-12-21
  • 2013-10-20
  • 2015-06-08
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多