Created
March 23, 2011 22:49
-
-
Save dehowell/884204 to your computer and use it in GitHub Desktop.
Python function to test if a file at a URL exists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib2 | |
def file_exists(location): | |
request = urllib2.Request(location) | |
request.get_method = lambda : 'HEAD' | |
try: | |
response = urllib2.urlopen(request) | |
return True | |
except urllib2.HTTPError: | |
return False |
I rewrote this function for Python 3:
import urllib.request def url_is_alive(url): """ Checks that a given URL is reachable. :param url: A URL :rtype: bool """ request = urllib.request.Request(url) request.get_method = lambda: 'HEAD' try: urllib.request.urlopen(request) return True except urllib.request.HTTPError: return False
For it to be compatible in both Python 2 and 3, I think you could just import
urllib
fromsix
:from six.moves import urllib
tried with url https://images.lululemon.com/is/image/lululemon/LW9BAWR_0919_1
The program hangs and operation timed out
hi guys, i rewrote this function
`def url_is_alive(url):
"""
Checks that a given URL is reachable.
:param url: A URL
:rtype: bool
"""
try:
response = urllib.request.urlopen(url)
status_code = response.getcode()
if status_code == 200:
return True
else:
return False
except urllib.request.HTTPError:
return False
`
Updated version I wrote:
def is_urlfile(url):
# Check if online file exists
try:
r = urllib.request.urlopen(url) # response
return r.getcode() == 200
except urllib.request.HTTPError:
return False
Hello ,
i wanna fetch file in server with authentication,i try this :
values = {"username": "user", "password": "password"} try: r = urllib.request.urlopen(url, values) # response return r.getcode() == 200 except urllib.request.HTTPError: return False
but thasnt work, can u help me please
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get no return. i use the python3 script. i did url = https://some.url.file.zip but get neither True nor False