
来源:【公众号】
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
2025被称为“AI元年”,而AI,与数据密不可分。网易公司创始人丁磊在《AI思维:从数据中创造价值的炼金术》一书中指出:AI思维, ...
2025-07-17数据分析师的技能图谱:从数据到价值的桥梁 在数据驱动决策的时代,数据分析师如同 “数据翻译官”,将冰冷的数字转化为清晰的 ...
2025-07-17Pandas 写入指定行数据:数据精细化管理的核心技能 在数据处理的日常工作中,我们常常需要面对这样的场景:在庞大的数据集里精 ...
2025-07-17解码 CDA:数据时代的通行证 在数字化浪潮席卷全球的今天,当企业决策者盯着屏幕上跳动的数据曲线寻找增长密码,当科研人员在 ...
2025-07-17CDA 精益业务数据分析:数据驱动业务增长的实战方法论 在企业数字化转型的浪潮中,“数据分析” 已从 “加分项” 成为 “必修课 ...
2025-07-16MySQL 中 ADD KEY 与 ADD INDEX 详解:用法、差异与优化实践 在 MySQL 数据库表结构设计中,索引是提升查询性能的核心手段。无论 ...
2025-07-16解析 MySQL Update 语句中 “query end” 状态:含义、成因与优化指南 在 MySQL 数据库的日常运维与开发中,开发者和 DBA 常会 ...
2025-07-16如何考取数据分析师证书:以 CDA 为例 在数字化浪潮席卷各行各业的当下,数据分析师已然成为企业挖掘数据价值、驱动决策的 ...
2025-07-15CDA 精益业务数据分析:驱动企业高效决策的核心引擎 在数字经济时代,企业面临着前所未有的数据洪流,如何从海量数据中提取有 ...
2025-07-15MySQL 无外键关联表的 JOIN 实战:数据整合的灵活之道 在 MySQL 数据库的日常操作中,我们经常会遇到需要整合多张表数据的场景 ...
2025-07-15Python Pandas:数据科学的瑞士军刀 在数据驱动的时代,面对海量、复杂的数据,如何高效地进行处理、分析和挖掘成为关键。 ...
2025-07-15用 SQL 生成逆向回滚 SQL:数据操作的 “后悔药” 指南 在数据库操作中,误删数据、错改字段或误执行批量更新等问题时有发生。 ...
2025-07-14t检验与Wilcoxon检验的选择:何时用t.test,何时用wilcox.test? t 检验与 Wilcoxon 检验的选择:何时用 t.test,何时用 wilcox. ...
2025-07-14AI 浪潮下的生存与进阶: CDA数据分析师—开启新时代职业生涯的钥匙(深度研究报告、发展指导白皮书) 发布机构:CDA数据科 ...
2025-07-13LSTM 模型输入长度选择技巧:提升序列建模效能的关键 在循环神经网络(RNN)家族中,长短期记忆网络(LSTM)凭借其解决长序列 ...
2025-07-11CDA 数据分析师报考条件详解与准备指南 在数据驱动决策的时代浪潮下,CDA 数据分析师认证愈发受到瞩目,成为众多有志投身数 ...
2025-07-11数据透视表中两列相乘合计的实用指南 在数据分析的日常工作中,数据透视表凭借其强大的数据汇总和分析功能,成为了 Excel 用户 ...
2025-07-11尊敬的考生: 您好! 我们诚挚通知您,CDA Level I和 Level II考试大纲将于 2025年7月25日 实施重大更新。 此次更新旨在确保认 ...
2025-07-10BI 大数据分析师:连接数据与业务的价值转化者 在大数据与商业智能(Business Intelligence,简称 BI)深度融合的时代,BI ...
2025-07-10SQL 在预测分析中的应用:从数据查询到趋势预判 在数据驱动决策的时代,预测分析作为挖掘数据潜在价值的核心手段,正被广泛 ...
2025-07-10