मैं एक यूआरएल (यानी 200, 404, आदि) से एक HTTP प्रतिक्रिया कोड प्राप्त करने का एक त्वरित तरीका ढूंढ रहा हूं। मुझे यकीन नहीं है कि किस लाइब्रेरी का उपयोग करना है।
जवाबों:
अद्भुत अनुरोध लाइब्रेरी का उपयोग करके अपडेट करें । ध्यान दें कि हम 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")
requestsदेता है 403, हालांकि यह अभी भी ब्राउज़र में काम कर रहा है।
यहां एक समाधान है जो 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
exceptब्लॉक को कम से कम प्रतिबंधित करना चाहिए StandardErrorताकि आप गलत तरीके से चीजों को पकड़ न सकें KeyboardInterrupt।
curl -I http://www.amazon.com/।
आपको इस तरह से 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]
http://entrian.com/गया http://entrian.com/blog, तो परिणामी 200 सही होगा, भले ही इसमें http://entrian.com/blog/(अनुप्रेक्षा स्लैश पर ध्यान दें) अनुप्रेषित शामिल हो ।
urllib2.HTTPErrorअपवाद एक शामिल नहीं है getcode()विधि। codeइसके बजाय विशेषता का उपयोग करें ।
यहाँ एक 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