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("segmentfault.com") # prints 200
print get_status_code("segmentfault.com", "/nonexistant") # prints 404
參考文章:Python實用腳本清單
http不只
get
方法(請求頭部
+正文
),還有head
方法,只請求頭部
。你用
get
請求就會請求整個頭部
+正文
, 可以試下head
方法, 直接訪問頭部!