Python 抓取知乎几千张小姐姐图片是什么体验?

来源:Python 技术「ID: pythonall」

知乎上有许多关于颜值、身材的话题,有些话题的回复数甚至高达几百上千,拥有成千上万的关注者与被浏览数。如果我们在摸鱼的时候欣赏这些话题将花费大量的时间,可以用 Python 制作一个下载知乎回答图片的小脚本,将图片下载到本地。

请求 URL 分析

首先打开 F12 控制台面板,看到照片的 URL 都是 https://pic4.zhimg.com/80/xxxx.jpg?source=xxx 这种格式的。

滚动知乎页面向下翻页,找到一个带 limit,offset 参数的 URL 请求。

检查 Response 面板中的内容是否包含了图片的 URL 地址,其中图片地址 URL 存在 data-original 属性中。

提取图片的 URL

从上图可以看出图片的地址存放在 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 爬虫制作了一个小脚本,如果小伙伴们觉得文章有趣且有用,点个 在看 支持一下吧!

(0)

相关推荐

  • Python爬取某网站文档数据完整教程(附源码)

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 基本开发环境 Python 3.6 Pycharm 相关模块的使用 import osimp ...

  • Python爬取某平台短视频的方法

    这篇文章主要介绍了Python爬取某平台短视频的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 前言 本文的文字及图片来源于网络,仅供学习.交流使用,不 ...

  • Python爬虫入门教程(十四):爬取有声小说网站数据

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. Python爬虫.数据分析.网站开发等案例教程视频免费在线观看 https://space. ...

  • Python 小技能之抓取天气信息发送给小姐姐

    来源:Python 技术「ID: pythonall」 每天一个 Python 小技巧,你学废了吗?今天文章主要讲解如何将天气预报信息爬取下来并发送给小姐姐,感兴趣的朋友不妨试试,说不定会有意外收获呢 ...

  • 随着身子的一阵颤抖,Python爬取抖音上的小姐姐突然变得索然无味

    在抖音刚出的那会 小帅b就被抖音上 的小姐姐迷得不行 毕竟在现实生活中 小帅b比较宅 很少遇到一些这样的小姐姐 除非小姐姐自己上门 (开玩笑开玩笑) 她们 说话好听 貌美如花 人又善良 皮肤光滑 身材 ...

  • 30分钟教会你爬取网站高清小姐姐图片,Python零基础爬虫入门

    30分钟教会你爬取网站高清小姐姐图片,Python零基础爬虫入门

  • Python抓取必应搜索背景图片

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 以下文章来源于编码珠玑 ,作者刘亚曦 Python爬虫.数据分析.网站开发等案例教程视频免费在线观 ...

  • 用 Python 抓取公号文章保存成 PDF

    今天为大家介绍如何将自己喜欢的公众号的历史文章转成 PDF 保存到本地.前几天还有朋友再问,能不能帮把某某公众号的文章下载下来,因为他很喜欢这个号的文章,但由于微信上查看历史文章不能排序,一些较早期的 ...

  • 用 Python 抓取公号文章保存成 HTML

    上次为大家介绍了如果用 Python 抓取公号文章并保存成 PDF 文件存储到本地.但用这种方式下载的 PDF 只有文字没有图片,所以只适用于没有图片或图片不重要的公众号,那如果我想要图片和文字下载下 ...

  • Python 抓取网页乱码原因分析

    在用 python2 抓取网页的时候,经常会遇到抓下来的内容显示出来是乱码. 发生这种情况的最大可能性就是编码问题:运行环境的字符编码和网页的字符编码不一致. 比如,在 windows 的控制台(gb ...

  • 爬虫实战:抓取知乎问题“大学生如何赚到一万元”

    最近对赚钱的话题很感兴趣,在知乎上关注了很多"赚钱"相关的问题,高质量的有不少,但是夹杂着私货的也不少.不过知乎的数据比较全,我们完全可以用来做文本分析. 爬虫的原理我就不细讲了, ...

  • 『爬虫四步走』手把手教你使用Python抓取并存储网页数据!

    爬虫是Python的一个重要的应用,使用Python爬虫我们可以轻松的从互联网中抓取我们想要的数据,本文将基于爬取B站视频热搜榜单数据并存储为例,详细介绍Python爬虫的基本流程.如果你还在入门爬虫 ...