2009-07-16 11 views
56

मैं एक यूआरएल से HTTP प्रतिक्रिया कोड प्राप्त करने का एक त्वरित तरीका ढूंढ रहा हूं (यानी 200, 404, आदि)। मुझे यकीन नहीं है कि कौन सी लाइब्रेरी का उपयोग करना है।किसी URL से HTTP प्रतिक्रिया कोड प्राप्त करने का सबसे अच्छा तरीका क्या है?

उत्तर

22

आप इस तरह 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 प्रतिसाद नहीं मिलेगा। – sorin

+1

@ सोरीन: यह निर्भर करता है - आप ** ** ** ** रीडायरेक्ट का पालन करना चाहते हैं। शायद आप सवाल पूछना चाहते हैं "अगर मैं ब्राउज़र के साथ इस यूआरएल पर जाना चाहता हूं, तो क्या यह सामग्री दिखाएगा या कोई त्रुटि देगा?" उस स्थिति में, अगर मैंने अपने उदाहरण में 'http: // entrian.com /' 'http: // entrian.com/blog' को बदल दिया है, तो परिणामी 200 सही होगा, भले ही इसमें 'http:// entrian.com/ब्लॉग/'(पिछला स्लैश नोट करें)। HEAD अनुरोध के लिए – RichieHindle

63

यहाँ एक समाधान के बजाय 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 
+13

+1 - किसी स्थिति की जांच के लिए पूरी इकाई को पुनर्प्राप्त करने की आवश्यकता नहीं है। –

+7

यद्यपि आपको वास्तव में 'सिवाय' ब्लॉक को कम से कम 'मानक त्रुटि' तक सीमित करना चाहिए ताकि आप 'कीबोर्ड इंटरप्ट' जैसी चीज़ों को गलत तरीके से पकड़ न सकें। –

+0

अच्छा विचार, बेन। मैंने तदनुसार इसे अद्यतन किया। –

3

urllib2.HTTPError अपवाद एक getcode() विधि शामिल नहीं है। इसके बजाय code विशेषता का उपयोग करें।

+2

यह मेरे लिए पाइथन 2.6 का उपयोग करता है। – RichieHindle

5

भविष्य में, उन लोगों के लिए जो Python3 और बाद में उपयोग करते हैं, यहां प्रतिक्रिया कोड खोजने के लिए एक और कोड है।

import urllib.request 

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

यह 404, 500 इत्यादि जैसे स्टेटस कोड के लिए HTTPError बढ़ाएगा –

63

अद्भुत requests library का उपयोग करके अपडेट करें। ध्यान दें कि हम HEAD अनुरोध का उपयोग कर रहे हैं, जो पूर्ण GET या POST अनुरोध के बाद और अधिक तेज़ी से होनी चाहिए।

import requests 
try: 
    r = requests.head("http://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") 
+0

अनुरोध ऐसे लिंक के लिए urllib2 से काफी बेहतर है: http://www.dianping.com/promo/208721#mod=4, urllib2 मुझे एक 404 और अनुरोध 200 के रूप में एक ब्राउज़र से मिलता है। – WKPlus

+5

httpstatusrappers.com ... कमाल !! मेरा कोड उस लिल जॉन की स्थिति पर है, बेटा! – tmthyjames

+1

यह सबसे अच्छा समाधान है। दूसरों में से किसी से भी बेहतर है। रिकॉर्ड के लिए – Awn

1

यहाँ एक httplib समाधान है कि urllib2 की तरह बर्ताव करता है। आप इसे सिर्फ एक यूआरएल दे सकते हैं और यह सिर्फ काम करता है। मेजबाननाम और पथ में अपने यूआरएल को विभाजित करने के बारे में गड़बड़ की जरूरत नहीं है। यह फ़ंक्शन पहले से ही करता है।

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 यूआरएल के साथ काम करता है। यह HTTP की HEAD विधि का उपयोग करता है। –

संबंधित मुद्दे

 संबंधित मुद्दे