Python 实现知乎图片批量抓取与筛选

一颗松果
一颗松果
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍一个基于Python的简单图片爬虫程序,旨在帮助用户批量保存知乎问题中的图片。程序通过Requests库模拟浏览器请求获取页面数据,利用BeautifulSoup解析HTML提取图片链接,并根据图片尺寸过滤头像和小图标。文中提供了使用PIL、OpenCV和skimage等多种方式处理图片的代码示例,适用于对网页图片抓取有基础需求的开发者。

Python 实现知乎图片批量抓取与筛选

在使用知乎时,有时需要将特定问题下的图片集中保存。为此编写了这个程序。该程序是一个基础版的图片爬虫,仅能抓取当前页面已加载的图片。由于对部分技术细节掌握有限,此处仅作简要说明并记录代码,不进行深入讲解。有兴趣的用户可直接使用,经测试在知乎等网站上运行有效。

前文曾介绍过通过 URL 打开图片的方法,其目的是在保存前先预览抓取到的图片效果,以便进行筛选。

本程序使用 requests 库获取页面信息。需要注意的是,请求时必须添加 header 参数,将程序伪装成浏览器访问服务器,否则可能被服务器拒绝。随后使用 BeautifulSoup 过滤冗余信息以获取图片地址。获取图片后,根据图片大小过滤掉头像、表情包等小尺寸图片。最后,在打开或保存图片时,可根据需求选择 OpenCV、skimage 或 PIL 等库。

程序代码如下:

# -*- coding=utf-8 -*-
import requests as req
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
import os
from skimage import io

url = "https://www.zhihu.com/question/37787176"
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Mobile Safari/537.36'}
response = req.get(url,headers=headers)
content = str(response.content)
#print content

soup = BeautifulSoup(content,'lxml')
images = soup.find_all('img')
print u"共有%d张图片" % len(images)

if not os.path.exists("images"):
  os.mkdir("images")

for i in range(len(images)):
  img = images[i]
  print u"正在处理第%d张图片..." % (i+1)
  img_src = img.get('src')
  if img_src.startswith("http"):
    ## use PIL
    '''
    print img_src
    response = req.get(img_src,headers=headers)
    image = Image.open(BytesIO(response.content))
    w,h = image.size
    print w,h
    img_path = "images/" + str(i+1) + ".jpg"
    if w>=500 and h>500:
      #image.show()
      image.save(img_path)

    '''

    ## use OpenCV
    import numpy as np
    import urllib
    import cv2

    resp = urllib.urlopen(img_src)

    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    w,h = image.shape[:2]
    print w,h
    img_path = "images/" + str(i+1) + ".jpg"
    if w>=400 and h>400:
      cv2.imshow("Image", image)
      cv2.waitKey(3000)
      ##cv2.imwrite(img_path,image)

    ## use skimage

    ## image = io.imread(img_src)
    ## w,h = image.shape[:2]
    ## print w,h
    #io.imshow(image)
    #io.show()

    ## img_path = "images/" + str(i+1) + ".jpg"
    ## if w>=500 and h>500:
      ## image.show()
      ## image.save(img_path)
      ## io.imsave(img_path,image)

print u"处理完成!"

此处提供了多种处理图片的选择,供参考。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表