温馨提示×

python怎么批量爬取并保存图片

小亿
85
2023-12-21 11:41:33
栏目: 编程语言

在Python中,可以使用第三方库如requests和BeautifulSoup来进行批量爬取并保存图片。

首先,需要安装相应的第三方库。可以使用以下命令安装:

pip install requests
pip install beautifulsoup4

下面是一个简单的示例代码,用于批量爬取并保存图片:

import requests
from bs4 import BeautifulSoup
import os

# 定义要爬取的网页链接
url = "http://example.com"

# 发送GET请求,获取网页内容
response = requests.get(url)

# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, "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["src"]

    # 发送GET请求,获取图片内容
    img_response = requests.get(img_url)

    # 提取图片名称
    img_name = img_url.split("/")[-1]

    # 保存图片到本地文件夹
    with open("images/" + img_name, "wb") as f:
        f.write(img_response.content)

    print("已保存图片:" + img_name)

上述代码会在当前目录下创建一个名为images的文件夹,并将爬取到的图片保存在该文件夹中。

请注意,该代码仅适用于简单的静态网页。对于需要登录或通过其他方式才能访问的网页,还需要进行额外的处理。

0