2014-09-29 21 views
1

所以我的python程序需要能夠ping一個網站,看看它是否啓動,我做了ping程序,然後發現這個網站只與httping一起工作,做了一些Google搜索後它在這個問題上幾乎找不到任何東西。有沒有人在Python中httping?如果是的話,你是怎麼做到的?感謝你的幫助。
這裏是我的正常的ping代碼(這工作,但沒有爲網站我需要它的工作)在python中HTTping

import os 
hostname = "sitename" 
response = os.system("ping -c 1 " + hostname) 
if response == 0: 
    print "good" 
else: 
    print "bad" 
+0

什麼是httping? – 2014-09-29 14:18:43

+0

ping不是http協議的一部分(它實際上是IMCP),你是什麼意思?你需要檢查一個網站是否可用?你需要特定的迴應嗎?請添加更多信息 – 2014-09-29 14:20:15

+2

[httping](https://github.com/flok99/httping)只是簡單地發送一個HTTP請求並測量所花費的時間。在Python中,您可以使用請求及其[已過](http://docs.python-requests.org/en/latest/api/?highlight=elapsed#requests.Response.elapsed)參數來完成此操作。 – 2014-09-29 14:20:19

回答

5

使用requests做出HTTP HEAD request

import requests 

response = requests.head("http://www.example.com/") 
if response.status_code == 200: 
    print(response.elapsed) 
else: 
    print("did not return 200 OK") 

輸出:

0:00:00.238418 
2

要檢查HTTP服務器的可訪問性,你可以做一個GET請求的URL,這是一樣容易:

import urllib2 
response = urllib2.urlopen("http://example.com/foo/bar") 
print response.getcode()