python爬虫爬取图片的简单代码

yizhihongxing

下面是关于"python爬虫爬取图片的简单代码"的完整攻略和示例说明:

什么是Python爬虫?

Python爬虫是指使用Python编写程序,自动化地从网站抓取数据。Python爬虫是一种非常强大的工具,使用它,可以快速地获取大量的数据。

如何使用Python爬虫抓取图片?

爬取图片的过程和爬取普通的文本信息的过程大体相似,只是需要使用不同的方法来下载和处理图片数据。

第一步:确定需要爬取的图片网址

首先需要确定需要爬取的图片所在的网址。可以通过查看网页源代码或者使用浏览器的开发者工具来确定。

第二步:分析网页结构

在确定了需要爬取的图片网址之后,需要对网页结构进行分析,找到包含需要爬取图片的HTML元素,进而确定获取图片的方法。一般情况下,图片都是以img标签的形式出现在页面上。

第三步:编写Python爬虫程序

有了前两步的准备工作,就可以开始编写Python爬虫程序了。下面是一个简单的示例代码,可以实现爬取指定网页中的所有图片并保存到本地:

import requests
from bs4 import BeautifulSoup
import os

def download_image(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            file_name = url.split('/')[-1]
            file_path = os.path.join(save_dir, file_name)
            with open(file_path, 'wb') as f:
                f.write(response.content)
                print('Downloaded image: %s' % url)
        else:
             print('Failed to download image: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

def crawl_images(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            soup = BeautifulSoup(response.content, 'html.parser')
            for img in soup.find_all('img'):
                img_url = img.get('src')
                if img_url is not None and 'http' in img_url:
                    download_image(img_url, save_dir)
        else:
            print('Failed to crawl images from: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

url = 'https://www.example.com/images/'
save_dir = './images/'
if not os.path.exists(save_dir):
    os.mkdir(save_dir)
crawl_images(url, save_dir)

通过以上程序,可以爬取指定URL下的所有图片并保存到本地。程序中使用了Requests库和BeautifulSoup库来实现爬虫的功能。其中,download_image函数负责下载单个图片,crawl_images函数负责爬取整个网站中的所有图片。

示例1:爬取cn.bing.com上的每日一图

import requests
import os

def download_image(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            file_name = url.split('/')[-1]
            file_path = os.path.join(save_dir, file_name)
            with open(file_path, 'wb') as f:
                f.write(response.content)
                print('Downloaded image: %s' % url)
        else:
             print('Failed to download image: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

def crawl_images(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            image_url = 'https://cn.bing.com' + response.json()['images'][0]['url']
            download_image(image_url, save_dir)
        else:
            print('Failed to crawl images from: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'
save_dir = './images/'
if not os.path.exists(save_dir):
    os.mkdir(save_dir)
crawl_images(url, save_dir)

通过此程序可以爬取bing.com的每日一图,并保存到指定的文件夹内。

示例2:爬取Unsplash上的高清壁纸

import requests
from bs4 import BeautifulSoup
import os

def download_image(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            file_name = url.split('/')[-1]
            file_path = os.path.join(save_dir, file_name)
            with open(file_path, 'wb') as f:
                f.write(response.content)
                print('Downloaded image: %s' % url)
        else:
             print('Failed to download image: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

def crawl_images(url, save_dir):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            soup = BeautifulSoup(response.content, 'html.parser')
            for img in soup.find_all('img'):
                img_url = img.get('src')
                if 'photo-' in img_url:
                    img_url = 'https:' + img_url.split('?')[0] + '?auto=compress&cs=tinysrgb&h=750&w=1260'
                    download_image(img_url, save_dir)
        else:
            print('Failed to crawl images from: %s' % url)
    except Exception as e:
        print('Error: %s' % e)

url = 'https://unsplash.com/s/photos/wallpapers'
save_dir = './wallpapers/'
if not os.path.exists(save_dir):
    os.mkdir(save_dir)
crawl_images(url, save_dir)

通过此程序可以爬取Unsplash上的高清壁纸,并保存到指定的文件夹内。注意,此网站的图片URL需要处理后才能直接下载使用。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python爬虫爬取图片的简单代码 - Python技术站

(0)
上一篇 2023年5月14日
下一篇 2023年5月14日

相关文章

  • python3 打印输出字典中特定的某个key的方法示例

    当我们需要在 Python3 中打印输出字典中特定的某个key时,可以使用字典变量名加上中括号来获取该值。具体方法如下: my_dict = {‘name’: ‘Lucy’, ‘age’: 18, ‘gender’: ‘female’} print(my_dict[‘name’]) # 输出结果为Lucy 上述代码中,我们创建了一个名为 my_dict 的字…

    python 2023年5月13日
    00
  • PyQt5每天必学之弹出消息框

    我来详细讲解一下“PyQt5每天必学之弹出消息框”的完整攻略。 弹出消息框 弹出消息框是GUI应用程序中一个常见的功能。在PyQt5中,我们可以使用QMessageBox类来实现弹出消息框的效果。QMessageBox提供了几种不同的消息框类型,包括信息框、警告框、错误框等。 下面是一个简单的示例,演示如何弹出一个信息框: from PyQt5.QtWidg…

    python 2023年5月20日
    00
  • 在Python中用一个切比雪夫数列除以另一个数列

    在Python中用一个切比雪夫数列除以另一个数列的完整攻略,需要分为以下几个步骤来完成。 1. 导入所需的库 需要导入numpy库,代码如下: import numpy as np 2. 准备数据 首先我们需要准备两个数列,分别表示被除数和除数。代码如下: numerator = np.array([1, 3, 5, 7]) denominator = np…

    python-answer 2023年3月25日
    00
  • Pytest断言的具体使用

    Pytest断言的具体使用 在Python中,Pytest是一个流行的测试框架,它提供了丰富的断言方法来验证代码的正确性。本文将介绍Pytest断言的具体使用,包括常用的断言方法和示例说明。 安装Pytest 在使用Pytest之前,我们需要先安装Pytest。可以使用pip命令在命令行安装Pytest: pip install pytest 常用的Pyte…

    python 2023年5月14日
    00
  • Python seaborn barplot画图案例

    接下来我将向您介绍如何使用Python Seaborn库来创建barplot(条形图)的完整攻略。 步骤一:导入必要的库和数据 我们需要先导入必要的Python库,包括Seaborn、Matplotlib和Pandas。同时,我们还需要加载我们想要绘制的数据集。在这个示例中,我们将使用Seaborn自带的数据集”tips”。 import seaborn a…

    python 2023年5月18日
    00
  • 使用python tkinter开发一个爬取B站直播弹幕工具的实现代码

    使用Python Tkinter开发一个爬取B站直播弹幕工具的实现代码可以分为以下步骤: 导入模块 import requests import json import re import tkinter as tk from tkinter import scrolledtext import threading import time 获取直播间id和弹…

    python 2023年6月13日
    00
  • Python实战小程序利用matplotlib模块画图代码分享

    下面是关于“Python实战小程序利用matplotlib模块画图代码分享”的完整攻略。 1. 安装matplotlib模块 在开始使用matplotlib模块绘图前,我们需要先安装matplotlib模块。可以在终端执行以下命令进行安装: pip install matplotlib 2. 导入matplotlib模块 安装完matplotlib模块后,在…

    python 2023年5月19日
    00
  • Python+unittest+requests+excel实现接口自动化测试框架

    以下是关于“Python+unittest+requests+excel实现接口自动化测试框架”的完整攻略: Python+unittest+requests+excel实现接口自动化测试框架 在 Python 中,我们可以使用 unittest 和 requests 模块实现接口自动化测试。同时,我们可以使用 excel 存储测试数据和测试结果。以下是 P…

    python 2023年5月15日
    00
合作推广
合作推广
分享本页
返回顶部