本文作者:铝哥

使用Python保存网页上的图片或者保存页面为截图

铝哥 2023-11-19 01:27:27

要使用Python保存网页上的图片或者保存页面为截图,我们可以使用`requests`库来获取网页内容,然后使用`BeautifulSoup`库来解析HTML并提取图片链接,接下来,我们可以使用`urllib`库来下载图片,或者使用`Pillow`库将整个网页截图保存为图片。

以下是详细的技术介绍:

使用Python保存网页上的图片或者保存页面为截图

1. 安装所需库

我们需要安装`requests`、`BeautifulSoup`和`Pillow`库,可以使用以下命令安装:

pip install requests beautifulsoup4 pillow

2. 获取网页内容

使用`requests`库的`get`方法获取网页内容,如下所示:

使用Python保存网页上的图片或者保存页面为截图
import requests

url = 'https://www.example.com'
response = requests.get(url)
html_content = response.text

3. 解析HTML并提取图片链接

使用`BeautifulSoup`库解析HTML内容,并提取图片链接,如果图片链接在``标签的`src`属性中,可以使用以下代码:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_content, 'html.parser')
img_tags = soup.find_all('img')
img_urls = [img['src'] for img in img_tags]

4. 下载图片或截图保存为图片

根据需要,可以选择下载单个图片或截图整个网页,以下是两个示例:

- 下载单个图片:

import urllib.request

def download_image(url, save_path):
    with urllib.request.urlopen(url) as response, open(save_path, 'wb') as out_file:
        return out_file.read()

# 使用方法:download_image(img_url, 'image_path.jpg')

- 截图保存为图片:

from PIL import ImageGrab
import io
import base64
import os

def save_screenshot(save_path):
    screen = ImageGrab.grab()
    img_byte_arr = io.BytesIO()
    screen.save(img_byte_arr, format='PNG')
    img_byte_arr = img_byte_arr.getvalue()
    with open(save_path, "wb") as f:
        f.write(base64.b64encode(img_byte_arr))
    del img_byte_arr # 删除字节对象以节省内存
    os.remove(save_path) # 删除临时文件(如果有)
    return True # 如果成功保存截图,返回True;否则返回False(例如,文件名已存在)

# 使用方法:save_screenshot('screenshot.png')

5. 完整代码示例:下载多个图片并保存到本地文件夹

def download_images(img_urls, save_dir):
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    for i, img_url in enumerate(img_urls):
        save_path = os.path.join(save_dir, f'image_{i}.jpg')
        try:
            download_image(img_url, save_path)
            print(f'Downloaded image {i}: {img_url} -> {save_path}')
        except Exception as e:
            print(f'Failed to download image {i}: {img_url} -> {e}')

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享