
来源:【公众号】
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 执行计划中 rows 数量的准确性解析:原理、影响因素与优化 在 MySQL SQL 调优中,EXPLAIN执行计划是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 对象的 text 与 content:区别、场景与实践指南 在 Python 进行 HTTP 网络请求开发时(如使用requests ...
2025-09-15CDA 数据分析师:激活表格结构数据价值的核心操盘手 表格结构数据(如 Excel 表格、数据库表)是企业最基础、最核心的数据形态 ...
2025-09-15Python HTTP 请求工具对比:urllib.request 与 requests 的核心差异与选择指南 在 Python 处理 HTTP 请求(如接口调用、数据爬取 ...
2025-09-12解决 pd.read_csv 读取长浮点数据的科学计数法问题 为帮助 Python 数据从业者解决pd.read_csv读取长浮点数据时的科学计数法问题 ...
2025-09-12CDA 数据分析师:业务数据分析步骤的落地者与价值优化者 业务数据分析是企业解决日常运营问题、提升执行效率的核心手段,其价值 ...
2025-09-12用 SQL 验证业务逻辑:从规则拆解到数据把关的实战指南 在业务系统落地过程中,“业务逻辑” 是连接 “需求设计” 与 “用户体验 ...
2025-09-11塔吉特百货孕妇营销案例:数据驱动下的精准零售革命与启示 在零售行业 “流量红利见顶” 的当下,精准营销成为企业突围的核心方 ...
2025-09-11CDA 数据分析师与战略 / 业务数据分析:概念辨析与协同价值 在数据驱动决策的体系中,“战略数据分析”“业务数据分析” 是企业 ...
2025-09-11Excel 数据聚类分析:从操作实践到业务价值挖掘 在数据分析场景中,聚类分析作为 “无监督分组” 的核心工具,能从杂乱数据中挖 ...
2025-09-10统计模型的核心目的:从数据解读到决策支撑的价值导向 统计模型作为数据分析的核心工具,并非简单的 “公式堆砌”,而是围绕特定 ...
2025-09-10CDA 数据分析师:商业数据分析实践的落地者与价值创造者 商业数据分析的价值,最终要在 “实践” 中体现 —— 脱离业务场景的分 ...
2025-09-10机器学习解决实际问题的核心关键:从业务到落地的全流程解析 在人工智能技术落地的浪潮中,机器学习作为核心工具,已广泛应用于 ...
2025-09-09SPSS 编码状态区域中 Unicode 的功能与价值解析 在 SPSS(Statistical Product and Service Solutions,统计产品与服务解决方案 ...
2025-09-09CDA 数据分析师:驾驭商业数据分析流程的核心力量 在商业决策从 “经验驱动” 向 “数据驱动” 转型的过程中,商业数据分析总体 ...
2025-09-09R 语言:数据科学与科研领域的核心工具及优势解析 一、引言 在数据驱动决策的时代,无论是科研人员验证实验假设(如前文中的 T ...
2025-09-08T 检验在假设检验中的应用与实践 一、引言 在科研数据分析、医学实验验证、经济指标对比等领域,常常需要判断 “样本间的差异是 ...
2025-09-08在商业竞争日益激烈的当下,“用数据说话” 已从企业的 “加分项” 变为 “生存必需”。然而,零散的数据分析无法持续为业务赋能 ...
2025-09-08随机森林算法的核心特点:原理、优势与应用解析 在机器学习领域,随机森林(Random Forest)作为集成学习(Ensemble Learning) ...
2025-09-05Excel 区域名定义:从基础到进阶的高效应用指南 在 Excel 数据处理中,频繁引用单元格区域(如A2:A100、B3:D20)不仅容易出错, ...
2025-09-05