 京公网安备 11010802034615号
			经营许可证编号:京B2-20210330
 京公网安备 11010802034615号
			经营许可证编号:京B2-20210330
		来源:【公众号】
Python技术
知乎上有许多关于颜值、身材的话题,有些话题的回复数甚至高达几百上千,拥有成千上万的关注者与被浏览数。如果我们在摸鱼的时候欣赏这些话题将花费大量的时间,可以用 Python 制作一个下载知乎回答图片的小脚本,将图片下载到本地。
首先打开 F12 控制台面板,看到照片的 URL 都是 https://pic4.zhimg.com/80/xxxx.jpg?source=xxx 这种格式的。
滚动知乎页面向下翻页,找到一个带 limit,offset 参数的 URL 请求。
检查 Response 面板中的内容是否包含了图片的 URL 地址,其中图片地址 URL 存在 data-original 属性中。
从上图可以看出图片的地址存放在 content 属性下的 data-original 属性中。
下面代码将获取图片的地址,并写入文件。
import re import requests import os import urllib.request import ssl from urllib.parse import urlsplit from os.path import basename import json
ssl._create_default_https_context = ssl._create_unverified_context
headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    'Accept-Encoding': 'gzip, deflate' } def get_image_url(qid, title):     answers_url = 'https://www.zhihu.com/api/v4/questions/'+str(qid)+'/answers?include=data%5B*%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cattachment%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Cis_labeled%2Cpaid_info%2Cpaid_info_content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_recognized%3Bdata%5B*%5D.mark_infos%5B*%5D.url%3Bdata%5B*%5D.author.follower_count%2Cbadge%5B*%5D.topics%3Bdata%5B*%5D.settings.table_of_content.enabled&offset={}&limit=10&sort_by=default&platform=desktop'     offset = 0     session = requests.Session()
    while True:
        page = session.get(answers_url.format(offset), headers = headers)
        json_text = json.loads(page.text)
        answers = json_text['data']
        offset += 10         if not answers:
            print('获取图片地址完成')
            return         pic_re = re.compile('data-original="(.*?)"', re.S)
        for answer in answers:
            tmp_list = []
            pic_urls = re.findall(pic_re, answer['content'])
            for item in pic_urls:  
                # 去掉转移字符                  pic_url = item.replace("", "")
                pic_url = pic_url.split('?')[0]
                # 去重复                 if pic_url not in tmp_list:
                    tmp_list.append(pic_url)
            
            for pic_url in tmp_list:
                if pic_url.endswith('r.jpg'):
                    print(pic_url)
                    write_file(title, pic_url) def write_file(title, pic_url):     file_name = title + '.txt'     f = open(file_name, 'a')
    f.write(pic_url + 'n')
    f.close()
示例结果:
下面代码将读取文件中的图片地址并下载。
def read_file(title):
    file_name = title + '.txt'     pic_urls = []
    # 判断文件是否存在
    if not os.path.exists(file_name):
        return pic_urls
    with open(file_name, 'r') as f:
        for line in f:
            url = line.replace("n", "")
            if url not in pic_urls:
                pic_urls.append(url)
    print("文件中共有{}个不重复的 URL".format(len(pic_urls)))
    return pic_urls
def download_pic(pic_urls, title):
    # 创建文件夹
    if not os.path.exists(title):
        os.makedirs(title)
    error_pic_urls = []
    success_pic_num = 0     repeat_pic_num = 0     index = 1     for url in pic_urls:
        file_name = os.sep.join((title,basename(urlsplit(url)[2])))
        if os.path.exists(file_name):
            print("图片{}已存在".format(file_name))
            index += 1             repeat_pic_num += 1             continue
        try:
            urllib.request.urlretrieve(url, file_name)
            success_pic_num += 1             index += 1             print("下载{}完成!({}/{})".format(file_name, index, len(pic_urls)))
        except:
            print("下载{}失败!({}/{})".format(file_name, index, len(pic_urls)))
            error_pic_urls.append(url)
            index += 1             continue
        
    print("图片全部下载完毕!(成功:{}/重复:{}/失败:{})".format(success_pic_num, repeat_pic_num, len(error_pic_urls)))
    if len(error_pic_urls) > 0:
        print('下面打印失败的图片地址')
        for error_url in error_pic_urls:
            print(error_url)
结语
今天的文章用 Python 爬虫制作了一个小脚本,如果小伙伴们觉得文章有趣且有用,点个 转发 支持一下吧!
 
                  数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在 MySQL 数据查询中,“按顺序计数” 是高频需求 —— 例如 “统计近 7 天每日订单量”“按用户 ID 顺序展示消费记录”“按产品 ...
2025-10-31在数据分析中,“累计百分比” 是衡量 “部分与整体关系” 的核心指标 —— 它通过 “逐步累加的占比”,直观呈现数据的分布特征 ...
2025-10-31在 CDA(Certified Data Analyst)数据分析师的工作中,“二分类预测” 是高频需求 —— 例如 “预测用户是否会流失”“判断客户 ...
2025-10-31在 MySQL 实际应用中,“频繁写入同一表” 是常见场景 —— 如实时日志存储(用户操作日志、系统运行日志)、高频交易记录(支付 ...
2025-10-30为帮助教育工作者、研究者科学分析 “班级规模” 与 “平均成绩” 的关联关系,我将从相关系数的核心定义与类型切入,详解 “数 ...
2025-10-30对 CDA(Certified Data Analyst)数据分析师而言,“相关系数” 不是简单的数字计算,而是 “从业务问题出发,量化变量间关联强 ...
2025-10-30在构建前向神经网络(Feedforward Neural Network,简称 FNN)时,“隐藏层数目设多少?每个隐藏层该放多少个神经元?” 是每个 ...
2025-10-29这个问题切中了 Excel 用户的常见困惑 —— 将 “数据可视化工具” 与 “数据挖掘算法” 的功能边界混淆。核心结论是:Excel 透 ...
2025-10-29在 CDA(Certified Data Analyst)数据分析师的工作中,“多组数据差异验证” 是高频需求 —— 例如 “3 家门店的销售额是否有显 ...
2025-10-29在数据分析中,“正态分布” 是许多统计方法(如 t 检验、方差分析、线性回归)的核心假设 —— 数据符合正态分布时,统计检验的 ...
2025-10-28箱线图(Box Plot)作为展示数据分布的核心统计图表,能直观呈现数据的中位数、四分位数、离散程度与异常值,是质量控制、实验分 ...
2025-10-28在 CDA(Certified Data Analyst)数据分析师的工作中,“分类变量关联分析” 是高频需求 —— 例如 “用户性别是否影响支付方式 ...
2025-10-28在数据可视化领域,单一图表往往难以承载多维度信息 —— 力导向图擅长展现节点间的关联结构与空间分布,却无法直观呈现 “流量 ...
2025-10-27这个问题问到了 Tableau 中两个核心行级函数的经典组合,理解它能帮你快速实现 “相对位置占比” 的分析需求。“index ()/size ( ...
2025-10-27对 CDA(Certified Data Analyst)数据分析师而言,“假设检验” 绝非 “套用统计公式的机械操作”,而是 “将模糊的业务猜想转 ...
2025-10-27在数字化运营中,“凭感觉做决策” 早已成为过去式 —— 运营指标作为业务增长的 “晴雨表” 与 “导航仪”,直接决定了运营动作 ...
2025-10-24在卷积神经网络(CNN)的训练中,“卷积层(Conv)后是否添加归一化(如 BN、LN)和激活函数(如 ReLU、GELU)” 是每个开发者都 ...
2025-10-24在数据决策链条中,“统计分析” 是挖掘数据规律的核心,“可视化” 是呈现规律的桥梁 ——CDA(Certified Data Analyst)数据分 ...
2025-10-24在 “神经网络与卡尔曼滤波融合” 的理论基础上,Python 凭借其丰富的科学计算库(NumPy、FilterPy)、深度学习框架(PyTorch、T ...
2025-10-23在工业控制、自动驾驶、机器人导航、气象预测等领域,“状态估计” 是核心任务 —— 即从含噪声的观测数据中,精准推断系统的真 ...
2025-10-23