2019-06-19 用Python批量下载新浪博客相册到本地计算机

新浪博客(http://blog.sina.com.cn)即将停止相册服务,在其中保存的珍贵的照片即将化为乌有。赶快下载保存起来。一个一个下太麻烦耗时了。于是用python编了一个小程序,分享给大家,也许你也用得着。

在电脑端登录你的新浪博客,然后你点页面上部的“图片”,
弹出新的页面提示:新浪博客“相册”功能下线公告 (相册导出功能开放到2019年7月31日24时,请您及时进行内容导出;)在最下面有一个“导出博客图片的链接” 按钮,
点击上面的按钮后可以保存得到一个xml文件。

为解决编码的问题,把xml文件打开,将其中全部内容复制到一个新建的txt文件中(weibo_images.txt)并保存。我的程序将读取此文件中的图片链接,一个一个自动下载保存。

python程序文件如下,供参考:

#==========================Start===================================

# Date: 2019-06-08

# Author: Mao Yuhong, 18621890022, yhmao@hotmail.com

#

# Brief:

# Download the image of the weibo blog

# image url list are stored in a xml file exported from the weibo blog website

import os

import re

import requests

# download folder and xml file

desktop =  os.path.join(os.path.expanduser("~"), 'Desktop')  #desktop path

folder = os.path.join(desktop, "WeiboBlogImagesDownloaded")  #photo save folder

if not os.path.exists(folder):

    os.makedirs(folder)

xml_file_path = r"C:\Users\yhmao\Desktop\weibo_images.txt"    #content of xml

# regular expression

r = re.compile('</?pic_\d+>',re.I)  #  url_image

r1 = re.compile('[_|>]',re.I)        # sequence number

r2 = re.compile('相册|>')            # subfolder

# success counter

count =0       

# read xml

url=xml_file_path

fp=open(url,'r',encoding='cp936')

# each line of the xml file

# if sub-category name, make a sub folder

# if image url, download and save

for line in fp:

    # subfolder, create subfolder

    if line.startswith('-<name_Live'):

        sub_folder = r2.split(line)[1]

        print(sub_folder)

        path = os.path.join(folder, sub_folder)

        print(path)

        # make dir

        if not os.path.exists(path):

            os.makedirs(path) 


    # image url, download image and save

    if line.startswith('<pic_'):               

        url_image = r.split(line)[1]                        # image url

        print(url_image)

        image_name = r1.split(line)[1] + '.jpg'            # id.jpg

        save_as_image = os.path.join(path, image_name)      # saveas target

        print(save_as_image)


        res = requests.get(url_image)                      # download and save

        img_file = open(save_as_image, 'wb')

        for chunk in res.iter_content(100000):

            img_file.write(chunk)

        img_file.close()


        count +=1            # counting success

# summary printout

print("\nTotal ", count, " files/images downloaded.")

print("Total ", count, " files/images saved on local computer")

print("at folder :", folder)

fp.close()

#==========================End===================================

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 周五的日子是和阿猫相见的时间,总是最开心的! 想着最近迷上了一本书,曲折,给人以激励!不只是读,更是品味。
    聂一一阅读 92评论 0 0
  • 世界上人大部分都有瘾,下意识的、自己都不知道的瘾。有时候你觉得自己只是沉迷于那个状态,殊不知它已经像一个感情黑洞一...
    十二里夏天阅读 529评论 1 0
  • 从上学的时候,我们就背诵这首诗,清明时节雨纷纷,这个清明也没有让我们失望,狂风加雨下的野餐别有一番滋味。 4月6号...
    未红的骆驼刺阅读 920评论 0 0