【问题标题】:I want to check if the website is ok我想检查网站是否正常
【发布时间】:2015-08-17 19:11:30
【问题描述】:

我想编写一个 python 代码来检查网站是否启动并运行,如果我输入一个随机的东西,比如“whatever”,程序会说:

“该网站无效。请尝试另一个。”

如果服务器没有启动,它会让我能够检查另一个 URL,程序会说:

“网站服务器未启动。请尝试另一个。”

再次检查另一个 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("--> ")

感谢所有的帮助:)

【问题讨论】:

  • 你写过这个程序吗?问题仅仅是您想更改错误消息吗?你能告诉我们你有什么吗?
  • @TigerhawkT3 刚刚做了 :)
  • 您使用的是哪个 python 版本? Python 3?
  • @svfat 实际上我使用的是 PyCharm 我不确定 python 的版本,但我在我的电脑上安装了 python 2.7

标签: python url exception web


【解决方案1】:

试试这个:

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("--> ")

【讨论】:

  • 这段代码适用于无效的网址,但如果我尝试使用“www.google.com”之类的网址,程序会显示“给定的网址无效”
  • 而且循环没有停止,我希望循环在一个有效的 URL 之后停止
  • 对,我认为这是因为网络服务器没有返回 200 响应代码,而是与重定向相关的内容,也许还检查 301 和 302?至于停止循环,只需在“站点已启动”输出后添加一个中断即可。
  • 大声笑我发现了错误!如果您添加 HTTP://,您的代码一切正常!!谢谢你!!!
【解决方案2】:
    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("--> ")

【讨论】:

    猜你喜欢
    • 2015-10-13
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2013-05-22
    相关资源
    最近更新 更多