Home > OS >  Check whether url exists or not without downloading the content using python
Check whether url exists or not without downloading the content using python

Time:12-23

I have to check whether url exists or not using python. I am trying to use requests.get(url) but it is taking alot of time as the file starts downloading as soon as get is hit. I don't want the file to be downloaded for checking the url validity. Can this be achieved using python ?

CodePudding user response:

Something like the below. See HTTP head for more info.

import requests
urls = ['https://www.google.com','https://www.google.com/you_can_not_find_me']
for idx,url in enumerate(urls,1):
  r = requests.head(url)
  if r.status_code == 200:
    print(f'{idx}) {url} was found')
  else:
    print(f'{idx}) {url} was NOT found')

output

1) https://www.google.com was found
2) https://www.google.com/you_can_not_find_me was NOT found

CodePudding user response:

Maybe this works for you?

import requests
r = requests.get('https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark.png')

if r.status_code == 200:
    choice = input("File available!\nDownload? Y/N: ").capitalize().strip()
    if choice == 'Y':
        with open('aim.png','wb') as f:
            f.write(r.content)
    else:
        print("Good bye!")
  • Related