====== Скачивание файла ====== [[ http://wiki.mihanik.net/doku.php?id=программирование_и_scripting:python:скачивание_файла&do=export_pdf | Экспорт в PDF ]] ~~ODT~~ Дата создания: 2022/04/19 17:16 (C) mihanik # # URL availability check function # Input: url - file URL # Exit: true - the file is available for download # false - the file is NOT available for download # def url_ok (url, timeout = 5): try: return urllib2.urlopen (url, timeout = timeout) .getcode () == 200 except urllib2.URLError as e: return False except socket.timeout as e: return False # Download file function # Input: From where we download the file (myurl), where we download the file (mypath) # Exit: true - successful download # false - download failed def my_downloadfile (myurl, mypath): if not url_ok (myurl, 5): print 'File NOT Available: ', myurl return False print 'File available:', myurl try: mycontent = urllib2.urlopen (myurl) output = open (mypath, 'wb') output.write (mycontent.read ()) except urllib2.HTTPError, error: print 'Error:', error.read () print 'File not downloaded', myurl return False except: print 'Something went wrong while downloading the file.', myurl return False else: print 'File downloaded.', myurl return True finally: output.close () [[#top|⇑ Наверх ⇑]]