Downloading a picture via urllib and python

后端 未结 18 1570
离开以前
离开以前 2020-11-22 10:35

So I\'m trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I\'ve found a few similar programs on here that do something simila

18条回答
  •  执念已碎
    2020-11-22 11:09

    Using requests

    import requests
    import shutil,os
    
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    }
    currentDir = os.getcwd()
    path = os.path.join(currentDir,'Images')#saving images to Images folder
    
    def ImageDl(url):
        attempts = 0
        while attempts < 5:#retry 5 times
            try:
                filename = url.split('/')[-1]
                r = requests.get(url,headers=headers,stream=True,timeout=5)
                if r.status_code == 200:
                    with open(os.path.join(path,filename),'wb') as f:
                        r.raw.decode_content = True
                        shutil.copyfileobj(r.raw,f)
                print(filename)
                break
            except Exception as e:
                attempts+=1
                print(e)
    
    if __name__ == '__main__':
        ImageDl(url)
    

提交回复
热议问题