京公网安备 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
机器学习的本质,是让模型通过对数据的学习,自主挖掘规律、实现预测与决策,而这一过程的核心驱动力,并非单一参数的独立作用, ...
2026-03-27在SQL Server数据库操作中,日期时间处理是高频核心需求——无论是报表统计中的日期格式化、数据筛选时的日期类型匹配,还是业务 ...
2026-03-27在CDA(Certified Data Analyst)数据分析师的能力体系与职场实操中,高维数据处理是高频且核心的痛点——随着业务场景的复杂化 ...
2026-03-27在机器学习建模与数据分析实战中,特征维度爆炸、冗余信息干扰、模型泛化能力差是高频痛点。面对用户画像、企业经营、医疗检测、 ...
2026-03-26在这个数据无处不在的时代,数据分析能力已不再是数据从业者的专属技能,而是成为了职场人、管理者、创业者乃至个人发展的核心竞 ...
2026-03-26在CDA(Certified Data Analyst)数据分析师的能力体系中,线性回归是连接描述性统计与预测性分析的关键桥梁,也是CDA二级认证的 ...
2026-03-26在数据分析、市场研究、用户画像构建、学术研究等场景中,我们常常会遇到多维度、多指标的数据难题:比如调研用户消费行为时,收 ...
2026-03-25在流量红利见顶、获客成本持续攀升的当下,营销正从“广撒网”的经验主义,转向“精耕细作”的数据驱动主义。数据不再是营销的辅 ...
2026-03-25在CDA(Certified Data Analyst)数据分析师的全流程工作中,无论是前期的数据探索、影响因素排查,还是中期的特征筛选、模型搭 ...
2026-03-25在当下数据驱动决策的职场环境中,A/B测试早已成为互联网产品、运营、营销乃至产品迭代优化的核心手段,小到一个按钮的颜色、文 ...
2026-03-24在统计学数据分析中,尤其是分类数据的分析场景里,卡方检验和显著性检验是两个高频出现的概念,很多初学者甚至有一定统计基础的 ...
2026-03-24在CDA(Certified Data Analyst)数据分析师的日常业务分析与统计建模工作中,多组数据差异对比是高频且核心的分析场景。比如验 ...
2026-03-24日常用Excel做数据管理、台账维护、报表整理时,添加备注列是高频操作——用来标注异常、说明业务背景、记录处理进度、补充关键 ...
2026-03-23作为业内主流的自助式数据可视化工具,Tableau凭借拖拽式操作、强大的数据联动能力、灵活的仪表板搭建,成为数据分析师、业务人 ...
2026-03-23在CDA(Certified Data Analyst)数据分析师的日常工作与认证考核中,分类变量的关联分析是高频核心场景。用户性别是否影响商品 ...
2026-03-23在数据工作的全流程中,数据清洗是最基础、最耗时,同时也是最关键的核心环节,无论后续是做常规数据分析、可视化报表,还是开展 ...
2026-03-20在大数据与数据驱动决策的当下,“数据分析”与“数据挖掘”是高频出现的两个核心概念,也是很多职场人、入门学习者容易混淆的术 ...
2026-03-20在CDA(Certified Data Analyst)数据分析师的全流程工作闭环中,统计制图是连接严谨统计分析与高效业务沟通的关键纽带,更是CDA ...
2026-03-20在MySQL数据库优化中,分区表是处理海量数据的核心手段——通过将大表按分区键(如时间、地域、ID范围)分割为多个独立的小分区 ...
2026-03-19在商业智能与数据可视化领域,同比、环比增长率是分析数据变化趋势的核心指标——同比(YoY)聚焦“长期趋势”,通过当前周期与 ...
2026-03-19