我想编写一个python代码来检查网站是否正常运行,如果我输入一个随机的东西,比如“无论”程序会说:
“该网站无效。请尝试其他网站。”
如果服务器未启动,它将使我能够检查另一个URL,程序会说:
“网站服务器未启动。请尝试其他服务器。”
再次检查另一个网址。 我已经尝试了这么久,总是得到一个我不想得到的异常,我想将异常更改为我选择的打印。
到目前为止我得到的是:import urllib
print ("Which website would you like to check?")
website_url = raw_input("--> ")
#The user will stuck in a loop until a valid website is exist, using the Application protocol
while urllib.urlopen(website_url).getcode() != 200:
print ("The website does not exist. Which website would you like to check?")
website_url = raw_input("--> ")
感谢所有帮助者:)
答案 0 :(得分:0)
试试这个:
import urllib
print ("Which website would you like to check?")
website_url = raw_input("--> ")
#The user will stuck in a loop until a valid website is exist, using the Application protocol
while True:
try:
if urllib.urlopen(website_url).getcode() != 200:
print ("The website does not exist. Which website would you like to check?")
else:
print "site is up"
except:
print "Invalid URL given"
website_url = raw_input("--> ")
答案 1 :(得分:-1)
import urllib
if website_url.split('//')[0] != 'http:' and website_url.split('//')[0] != 'https:': # Adds http:// to the given URL because it is the only way to check for server response
website_url = 'http://' + website_url
while True: #The user will stuck in a loop until a valid website is exist, using the Application protocol
try:
if urllib.urlopen(website_url).getcode() != 200:
print ("Invalid URL given. Which website would you like to check?")
website_url = raw_input("--> ")
else:
print ("The server is up")
break
except:
print ("Invalid URL given. Which website would you like to check?")
website_url = raw_input("--> ")