How to save an image on the internet to local file in Python -


i want take direct image links reddit , imgur, save them file, , upload them twitter. there no real reason i'm doing this, want practice new programming. unsure on how save image link file though. came across stackoverflow question asked same thing, , answer person given use urllib.retrieve.

this code using:

def post_to_twitter():     if 'i.redd.it/' in submission.url or 'i.imgur.com/' in submission.url:         print(submission.url)         urllib.urlretrieve(str(submission.url),'<my directory>')     elif 'i.redd.it/' not in submission.url or 'i.imgur.com/' not in submission.url:         print('no direct imgur or reddit image link') 

however, when run code, unicode error have never come across before - (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uxxxxxxxx escape , idle highlights comma used between submission url , chosen directory.

obviously wrong code, sure saving file using image link not easy using single line of code. i'm doing wrong, or there better way this? if possible, please explain i'm five. i'm new programming , don't understand words yet me confused.


i found solution.

i managed working original code used, tweaked.

i used:

urllib.request.urlretrieve(submission.url, 'reddit twitter downloaded images\\'+submission.id+'.jpeg') 

submission.url returns link image, can replace whatever want, long equal direct image link string, such my_url = "http://i.imgur.com/qjmif2a.gif"

'reddit twitter downloaded images\\'+submission.id+'.jpeg' name of image want save. can specify path in it. however, because can't manually specify want file save as, use submission.id file name, way can guarantee unique. add .jpeg @ end of specify file type.

try this:

import os import urllib.request import urllib.error def saveimg(url,path,name):     #url imgurl      #path folder      #name tmp.png     if not os.path.exists(path):         os.mkdir(path)     try:         response=urllib.request.urlopen(url);     except urllib.error.urlerror e:         return 0     except urllib.error.httperror e:         return 0     code=response.read()     filehandle=open(path+name,'wb');     filehandle.write(code)     filehandle.close()     return 1 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

angular - Copying node modules to wwwroot AspNetCore -