python下载博文中微博图床图片

python下载博文中微博图床图片

前言

昨天突然发现博客中的许多图片都挂了(会尽neng快tuo修jiu复tuo),今天看了下,发现很多人都挂了,嗯没错就是新浪搞的鬼了,目前是对referrer进行了限制,目前空的referrer还是可以访问的。小气吧啦的新浪,还是改用GitHub吧,ipic也不能用了(辣鸡新浪)。

但我的图片都没有备份…试了下手工去下载回来,但实在太慢,而且还可能漏…

只好写个爬虫了,幸好前面暴力破解的时候回忆了一下,写起来轻松许多

功能

在这里插入图片描述

直接用python运行py文件,然后根据博文提示输入博文的url

然后就会搜索页面中img标签包含sinaimg的url然后按先后顺序去下载,图片从1开始命名

下载会在当前目录下以url最后/后的字符建立一个的文件夹(所以url最后不要带/),图片会保存到此文件夹

(Windows下没有问题,mac下/好像不对,没有保存到正确位置,请需要者自行修改)

代码

import urllib.request
from lxml import etree
import ssl
import os

header={
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',  
    'Connection': 'keep-alive'
}

def get_content(url):
    global header
    context = ssl._create_unverified_context()
    request = urllib.request.Request(url = url, headers=header)
    response = urllib.request.urlopen(request, context=context).read().decode('utf-8')
    return response

def get_imgurl(content):
    html = etree.HTML(content)
    result = html.xpath('//img/@src')
    finnal_result = []
    for i in result:
        if "sinaimg" in i:
            finnal_result.append(i)
    return finnal_result

def download_img(urls, filepath):
    global header
    context = ssl._create_unverified_context()
    page = 0
    for i in urls:
        page += 1
        print('downloading ' + str(page) + '.jpg ...')
        imgfilepath = filepath + '\\' + str(page) + '.jpg'
        request = urllib.request.Request(url = i, headers=header)
        response = urllib.request.urlopen(request, context=context).read()
        with open(imgfilepath,'wb') as f:
            f.write(response)
    print('over!!!')

def main():
    url = input("input url:")
    #print(get_content(url))
    urls = get_imgurl(get_content(url))
    try:
        os.mkdir(url.split('/')[-1])
    except:
        pass
    filepath = os.getcwd()+ '\\' +url.split('/')[-1]
    download_img(urls, filepath)

if __name__ == "__main__":
    main()
发布了54 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_26406447/article/details/89588199