【问题标题】:404 error received for working url using python urllib2使用 python urllib2 工作 url 收到 404 错误
【发布时间】:2017-11-01 23:09:06
【问题描述】:

我正在尝试获取以下网址:ow dot ly/LApK30cbLKj 正在运行,但我收到 http 404 错误:

            my_url = 'ow' + '.ly/LApK30cbLKj'     # SO won't accept an ow.ly url
            headers = {'User-Agent' : user_agent } 
            request = urllib2.Request(my_url,"", headers)

            response = None
            try: 
                response = urllib2.urlopen(request)
            except urllib2.HTTPError, e:
                print '+++HTTPError = ' + str(e.code)

我可以做些什么来获得这个具有 http 200 状态的 url,就像我在浏览器中访问时所做的那样?

【问题讨论】:

  • @HughBothwell 是的,但我不让我发帖
  • 如果我使用请求而不是 urllib2,我会得到 HTTP 200,我认为这对你没有帮助,因为我知道你出于特定原因使用 urllib2。

标签: python http-status-code-404 urllib2


【解决方案1】:

你的例子对我有用,除了你需要添加 http://

my_url = 'http://ow' + '.ly/LApK30cbLKj'

【讨论】:

    【解决方案2】:

    你需要定义url的协议,问题是当你在浏览器中访问url时,默认的协议是HTTP。但是 urllib2 不会为你做,你需要在 url 的开头添加http://,否则会报错:

    ValueError: unknown url type: ow.ly/LApK30cbLKj
    

    【讨论】:

      【解决方案3】:

      正如@enjoi 提到的,我使用了请求:

      import requests
      
      result = None
                  try:
                      result = requests.get(agen_cont.source_url)
                  except requests.exceptions.Timeout as e:
                      print '+++timeout exception: ' 
                      print e
                  except requests.exceptions.TooManyRedirects as e:
                      print '+++ too manuy redirects exception: ' 
                      print e
                  except requests.exceptions.RequestException as e:
                      print '+++ request exception: ' 
                      print e
                  except Exception:
                      import traceback
                      print '+++generic exception: ' + traceback.format_exc()
      
                  if result:
                      final_url = result.url
                      print final_url
                      response = result.content
      

      【讨论】:

        猜你喜欢
        • 2015-09-01
        • 2012-04-24
        • 1970-01-01
        • 2017-04-17
        • 2013-06-22
        • 1970-01-01
        • 1970-01-01
        • 2016-01-18
        • 1970-01-01
        相关资源
        最近更新 更多