Home > Mobile >  How to check the connectivity for a URL in python
How to check the connectivity for a URL in python

Time:09-26

My requirement is almost same as Requests — how to tell if you're getting a success message?

But I need to print error whenever I could not reach the URL..Here is my try..

# setting up the URL and checking the conection by printing the status

url = 'https://www.google.lk'

try:
    page = requests.get(url)
    print(page.status_code)
except requests.exceptions.HTTPError as err:
    print("Error")

The issue is rather than printing just "Error" it prints a whole error msg as below.

Traceback (most recent call last):
  File "testrun.py", line 22, in <module>
    page = requests.get(url)
  File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='docs.microsoft.com', port=443): Max retries exceeded with url: /en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7ff91a543198>: Failed to establish a new connection: [Errno 110] Connection timed out',))

Can someone show me how should I modify my code to just print "Error" only if there is any issue? Then I can extend it to some other requirement.

CodePudding user response:

You're not catching the correct exception.

import requests


url = 'https://www.googlggggggge.lk'

try:
    page = requests.get(url)
    print(page.status_code)
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):
    print("Error")

you can also do except Exception, however note that Exception is too broad and is not recommended in most cases since it traps all errors

CodePudding user response:

You need to either use a general exception except or catch all exceptions that requests module might throw, e.g. except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError).

For full list see: Correct way to try/except using Python requests module?

  • Related