-1

Here is my code

import requests
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
    print ("Online")
else:
    print ("Offline")

It pings http://example.com. When the website is online it successfully prints Online. when the website is offline, I want it to print Offline but instead it is showing me a huge error message ends with this line

Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd3f17372e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))

How can I fix it to successfully print Offline if the website is offline?

Sadie
  • 35
  • 1
  • 6

2 Answers2

1

You're getting an error on request itself.

ping = requests.get('http://example.com')

So you don't get a status code if server didn't respond you. If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.

import requests
try:
    ping = requests.get('http://example.com')
    print ("Online")
except:
    print ("Offline")
  • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks. – Volodymyr Vyshnevskyi Mar 06 '19 at 15:03
1

You can do this by modifying your code as below:

Adding try and except mechanism.

import requests
try:
    ping = requests.get('http://example.com')
    ping.status_code

    if ping.status_code==200:
        print ("Online")
    else:
        print ("Offline")
except requests.exceptions.ConnectionError as e:
    print("Offline")
Devang Padhiyar
  • 3,427
  • 2
  • 22
  • 42