从URL获取HTTP响应代码的最佳方法是什么?


80

我正在寻找一种从URL(例如200、404等)获取HTTP响应代码的快速方法。我不确定要使用哪个库。

Answers:


98

使用精彩的请求库进行更新。请注意,我们使用的是HEAD请求,它比完整的GET或POST请求发生得更快。

import requests
try:
    r = requests.head("https://stackoverflow.com")
    print(r.status_code)
    # prints the int of the status code. Find more at httpstatusrappers.com :)
except requests.ConnectionError:
    print("failed to connect")

对于这样的链接,请求比urllib2好得多:dianping.com/promo/208721#mod=4,urllib2给我404,而请求给我200,就像从浏览器中得到的一样。
WKPlus 2013年

5
httpstatusrappers.com ...很棒!我的代码是关于Lil Jon的身份的,儿子!
tmthyjames 2014年

1
这是最好的解决方案。比其他任何一个都要好得多。
Awn

@WKPlus记录下来,尽管它仍在浏览器中运行,但现在为您requests提供403了链接。
丹尼斯·哥洛马佐夫

2
@古诺哈!那不是我想发表评论的意图,我认为这很好,在这种情况下,人们应该尝试理解为什么它在浏览器中“可以正常工作”,但是实际上返回的是403代码事情在两个地方都在发生。
西德斯

65

这是httplib替代使用的解决方案。

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None


print get_status_code("stackoverflow.com") # prints 200
print get_status_code("stackoverflow.com", "/nonexistant") # prints 404

14
HEAD请求+1 —无需检索整个实体进行状态检查。
本·布兰克

7
尽管您实际上应该except至少将限制限制在StandardError这样的范围内,以免导致错误捕获诸如此类的东西KeyboardInterrupt
本·布兰克

3
我想知道HEAD请求是否可靠。因为网站可能没有(正确)实现HEAD方法,这可能导致状态代码如404、501或500。或者我是否偏执?
布莱斯2012年

2
如何使它遵循301?
兰德尔·亨特2013年

2
@Blaise如果网站不允许HEAD请求,则执行HEAD请求导致405错误。有关此示例,请尝试运行curl -I http://www.amazon.com/
尼克

24

您应该使用urllib2,如下所示:

import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

# Prints:
# 200 [from the try block]
# 404 [from the except block]

3
这不是有效的解决方案,因为urllib2将跟随重定向,因此您将不会获得任何3xx响应。
索林2013年

1
@sorin:这取决于-您可能希望遵循重定向。也许您想问一个问题:“如果我要使用浏览器访问此URL,它将显示内容还是出现错误?” 在那种情况下,如果我在示例中更改http://entrian.com/http://entrian.com/blog,即使结果涉及重定向到http://entrian.com/blog/(注意末尾的斜杠),结果200也将是正确的。
RichieHindle 2013年

8

将来,对于那些使用python3及更高版本的用户,这是另一个代码来查找响应代码。

import urllib.request

def getResponseCode(url):
    conn = urllib.request.urlopen(url)
    return conn.getcode()

2
这将提高一个HTTPError为状态代码像404,500等
尼古拉斯- [R


2

在@nickanor的答案中提及@Niklas R的评论:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

0

这是一个httplib行为类似于urllib2的解决方案。您可以给它一个URL,它就可以工作。无需费心将URL拆分为主机名和路径。该功能已经做到了。

import httplib
import socket
def get_link_status(url):
  """
    Gets the HTTP status of the url or returns an error associated with it.  Always returns a string.
  """
  https=False
  url=re.sub(r'(.*)#.*$',r'\1',url)
  url=url.split('/',3)
  if len(url) > 3:
    path='/'+url[3]
  else:
    path='/'
  if url[0] == 'http:':
    port=80
  elif url[0] == 'https:':
    port=443
    https=True
  if ':' in url[2]:
    host=url[2].split(':')[0]
    port=url[2].split(':')[1]
  else:
    host=url[2]
  try:
    headers={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0',
             'Host':host
             }
    if https:
      conn=httplib.HTTPSConnection(host=host,port=port,timeout=10)
    else:
      conn=httplib.HTTPConnection(host=host,port=port,timeout=10)
    conn.request(method="HEAD",url=path,headers=headers)
    response=str(conn.getresponse().status)
    conn.close()
  except socket.gaierror,e:
    response="Socket Error (%d): %s" % (e[0],e[1])
  except StandardError,e:
    if hasattr(e,'getcode') and len(e.getcode()) > 0:
      response=str(e.getcode())
    if hasattr(e, 'message') and len(e.message) > 0:
      response=str(e.message)
    elif hasattr(e, 'msg') and len(e.msg) > 0:
      response=str(e.msg)
    elif type('') == type(e):
      response=e
    else:
      response="Exception occurred without a good error message.  Manually check the URL to see the status.  If it is believed this URL is 100% good then file a issue for a potential bug."
  return response

1
不知道为什么在没有反馈的情况下对此进行了否决。它适用于HTTP和HTTPS URL。它使用HTTP的HEAD方法。
Sam Gleske
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.