如何使用python爬图片

 一、说明

使用 Python 爬取图片(或其他类型的文件)通常是为了自动化从互联网上下载图片的过程,这样可以节省人工下载的时间和精力,尤其是在需要大量图片时,下面将介绍两种方法,方法二步骤稍微多些,但可以爬取防爬虫的网站上的图片。

二、准备

安装python,谷歌浏览器,下载chromedriver,注意chromedriver的版本必须兼容谷歌浏览器,否则在运行python代码时会报错,在windows操作系统下运行。

三、方法一代码

以下代码注意在使用前需安装requests beautifulsoup4,其指令已经注射在代码的开头,可自行拷贝到cmd内执行下载安装。使用时注意替换自己想爬取的图片网站,执行完后,会将图片自动下载到当前目录下的images文件夹下。注意该代码在防爬虫的网站无法下载图片;

# 使用前先安装pypthon.exe -m pip install requests beautifulsoup4 -i https://mirrors.aliyun.com/pypi/simple/


import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import shutil

# 清空 images 文件夹中的所有文件
def clear_images_folder():
    if os.path.exists('images'):
        shutil.rmtree('images')  # 删除整个文件夹及其内容
    os.makedirs('images')  # 重新创建空的 images 文件夹

# 设置 headers,模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}

# 清空文件夹
clear_images_folder()

# 爬取网页的图片
def download_images(url):
    # 发送HTTP请求获取网页内容
    response = requests.get(url, headers=headers)
    
    if response.status_code != 200:
        print(f"无法获取网页 {url},状态码: {response.status_code}")
        return
    
    # 解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 找到所有图片标签
    img_tags = soup.find_all('img')
    
    # 下载每个图片
    for img in img_tags:
        img_url = img.get('src')
        if not img_url:
            continue
        
        # 拼接完整的图片URL(如果URL是相对路径)
        img_url = urljoin(url, img_url)
        
        # 获取图片文件名
        img_name = os.path.basename(img_url)
        
        # 下载并保存图片
        try:
            img_data = requests.get(img_url).content
            with open(f'images/{img_name}', 'wb') as f:
                f.write(img_data)
            print(f"已下载: {img_name}")
        except Exception as e:
            print(f"下载失败: {img_name}, 错误: {e}")

# 示例:爬取豆瓣电影页面的图片
url = 'https://www.zhihu.com/question/382506475/answer/20689686702'  # 你可以替换为任何你想爬取的 URL
download_images(url)
print("下载完成")


四、方法二步骤

利用浏览器绕开防爬虫网站;

4.1下载chromedriver

网址:https://googlechromelabs.github.io/chrome-for-testing/,注意版本必须兼容谷歌浏览器,否则代码执行将会报错。谷歌浏览器的版本查看参考以下步骤。

4.1.1

点击右上角的三个点;

如何使用python爬图片_第1张图片

4.1.2

在帮助里点击关于,如下图所示就是谷歌浏览器的版本号;

如何使用python爬图片_第2张图片

4.2代码

该代码需告知chromedriver.exe的目录,使用前需在cmd下安装selenium,相关指令已经注释在代码开头。注意不支持数据url图片的下载。

#使用前安装pypthon.exe -m pip install selenium -i https://mirrors.aliyun.com/pypi/simple/
# (2)ChromeDriver 下载地址,注意使用时版本要和 Chrome 浏览器版本兼容
# https://googlechromelabs.github.io/chrome-for-testing/

import os
import shutil
import time
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from urllib.parse import urlparse

# 清空 images 文件夹中的所有文件
def clear_images_folder():
    if os.path.exists('images'):
        shutil.rmtree('images')  # 删除整个文件夹及其内容
    os.makedirs('images')  # 重新创建空的 images 文件夹

# 清空文件夹
clear_images_folder()

# 设置 Chrome 驱动选项
options = Options()
options.add_argument("--headless")  # 无头模式
options.add_argument("--disable-gpu")

# 设置 ChromeDriver 的路径
service = Service(executable_path='D:/AppData/chromedriver-win64/chromedriver.exe')  # 替换为实际的 ChromeDriver 路径

# 启动浏览器
driver = webdriver.Chrome(service=service, options=options)

# 打开网页
url = 'https://www.zhihu.com/question/382506475/answer/20689686702'  # URL
driver.get(url)

# 等待页面加载
time.sleep(3)

# 获取网页内容
html = driver.page_source

# 用 BeautifulSoup 解析网页
soup = BeautifulSoup(html, 'html.parser')

# 获取所有图片标签
img_tags = soup.find_all('img')

# 创建文件夹存储图片
if not os.path.exists('images'):
    os.makedirs('images')

# 下载图片
for img in img_tags:
    img_url = img.get('src')
    if img_url:
        # 排除 data URI 类型的图片
        if img_url.startswith('data:'):
            print(f"跳过数据URI图片: {img_url[:50]}...")  # 输出部分 URL,避免过长
            continue
        
        # 清理文件名,去除非法字符
        img_name = os.path.basename(img_url.split('?')[0])  # 删除 URL 中的查询参数部分
        img_name = img_name.replace(':', '_').replace('/', '_')  # 替换非法字符

        try:
            # 请求图片并保存
            img_data = requests.get(img_url).content
            with open(f'images/{img_name}', 'wb') as f:
                f.write(img_data)
            print(f"已下载: {img_name}")
        except Exception as e:
            print(f"下载失败: {img_name}, 错误: {e}")

# 关闭浏览器
driver.quit()
print("下载完成")




五、资源获取

相关工具,代码和安装包在开头的资源文件,如不想自行下载可直接下载笔者已经全部打包好的。

你可能感兴趣的:(python,开发语言)