python爬虫之:爬百度贴吧女神图片

244 阅读1分钟
本题主要练习简单爬虫、文件操作及正则表达式的应用。比较简单,关键在于多练习和思考。
代码如下:
import urllib.request
import re
import os

def get_imgurl(url='https://tieba.baidu.com/p/6043078959'):
    '''从帖子地址获取图片地址.
        传入:帖子地址
        传出:图片地址列表
    '''
    urlre=urllib.request.Request(url)
    response=urllib.request.urlopen(urlre)
    html=response.read().decode("utf-8")
    htmlelm=re.findall(r"https://imgsa.baidu.com/\w+?/.+?/.+?/\w+?.jpg",html)
    return htmlelm

def save_img(htmlelm):
    "保存图片"
    try:
        "尝试创建女神图片文件夹,已经存在也不要报错"
        os.mkdir(os.curdir+"/女神图片")
    except:
        pass
    os.chdir(os.curdir+"/女神图片") #跳转到'女神图片'文件夹准备存文件
    for i in htmlelm:   #循环存图,有多少图片循环多少次
        filename=i.split(sep="/")[-1]   #用‘/’分割地址,取最后一项作为图片名字
        print(filename)
        urlrew=urllib.request.Request(i)
        responsew=urllib.request.urlopen(urlrew)
        htmlw=responsew.read()
        with open(filename,'wb') as f:
            f.write(htmlw)
            
url=input("请输入要爬的贴吧地址:")
save_img(get_imgurl(url))
运行结果:

女神轻松下载到了 “女神图片”文件夹里,友情提醒各位:注意身体。