Python下载图片函数

在进行爬虫的时候,经常需要保存图片到本地。通常得先获得图片(.png,.jpg)的下载链接,再设置保存到本地的路径,因此函数传入的参数为url和path。

    def download_image(url,file_path):
        try:
            #header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.2.1000 Chrome/30.0.1599.101 Safari/537.36"}  
            html = requests.get(url)#, header) #视情况看是否需要添加header
            with open(file_path, 'ab') as file:
                file.write(html.content)
                file.close()
        except:
            dic = {'url':url, 'file_path':file_path}
            print("下载失败:", dic)

因为用到了requests,所以需要import requests。这个函数就可以下载图片到本地了。

猜你喜欢

转载自blog.csdn.net/qq_29303759/article/details/81430890
今日推荐