以下代码使用 Python 的 requests 和 BeautifulSoup 库,抓取网页上的图片并保存到本地。

import requests
from bs4 import BeautifulSoup
import os
import threading

# 网页链接
url = 'https://www.vcg.com/creative'

# 获取网页内容
try:
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
except Exception as e:
    print(f'获取网页内容出错:{e}')
    exit()

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

# 创建文件夹(如果不存在)
folder_path = 'D:/pt'
if not os.path.exists(folder_path):
    os.makedirs(folder_path)

# 去重集合
url_set = set()

# 下载图片函数
def download_img(img_url, file_path):
    try:
        img_data = requests.get(img_url).content
        with open(file_path, 'wb') as f:
            f.write(img_data)
    except Exception as e:
        print(f'下载图片 {img_url} 出错:{e}')

# 遍历所有图片标签,获取图片 URL,并保存到本地
threads = []
for img in img_tags:
    img_url = img.get('src')
    if img_url and 'http' in img_url and img_url not in url_set:
        url_set.add(img_url)
        file_name = img_url.split('/')[-1]
        file_path = os.path.join(folder_path, file_name)
        thread = threading.Thread(target=download_img, args=(img_url, file_path))
        threads.append(thread)
        thread.start()

代码可以正常运行,但需要注意以下几点:

  1. 需要先导入 requestsBeautifulSoup,否则会报错。
  2. 在获取网页内容时,需要加上异常处理,防止出现网络连接失败等问题。
  3. 下载图片时,需要加上异常处理,防止出现下载失败等问题。
  4. 可以使用多线程下载图片,提高下载速度。

希望本文能够帮助您更好地理解使用 Python 抓取网页图片并保存的流程。如果您有任何问题,请随时留言。

注意:

  • 代码中使用的 url 是一个示例,请根据您的实际需求进行修改。
  • folder_path 是保存图片的文件夹路径,请根据您的实际情况进行修改。
  • 在使用多线程下载图片时,请注意控制线程数量,避免造成服务器压力。
  • 抓取网站图片时,请注意网站的 robots.txt 文件,尊重网站的爬取规则。
Python 使用 requests 和 BeautifulSoup 抓取图片并保存 - 代码详解

原文地址: https://www.cveoy.top/t/topic/n23J 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录