Paython爬取网页所有图片并保存到本地

# coding=utf-8

from urllib import request
from bs4 import BeautifulSoup
import requests
# import urllib
import os

# 目标地址
url = "http://www.biqukan.com/"
# 像目标URL发送get请求
req = request.Request(url)
# 获取URL请求内容
response = request.urlopen(req)
# 读取返回的HTML内容
html = response.read()
print(html)

# 解析HTML
soup = BeautifulSoup(html, 'html.parser')

# 使用find_all方法查找HTML中所有<img>标签
all_img = soup.find_all('img')
print(all_img)

# 遍历所有爬取到的<img>
for img in all_img:
    scr = img['src']
    # 获取遍历<img>得到的图片src地址
    img_url = scr
    print(img_url)
    print(img)
    # 拼接图片下载完整地址
    img_full_url = url + img_url
    print(img_full_url)

    # 遍历获取图片名称
    for alt in all_img:
        print('alt = ', alt)

        # 定义存储位置
        root = "D://PythonDownload/test/"
        alt = img['alt']
        # 定义图片存储名称和格式
        # path = root + img_full_url.split('/')[-1] + ".jpg"     # 使用完整下载地址最后分割部分作为图片名称
        path = root + alt + ".png"

        try:
            # 判断路径是否存在
            if not os.path.exists(root):
                print('没有路径,请新建')
                os.mkdir(root)
            # 判断图片是否存在
            if not os.path.exists(path):
                print('文件夹没有图片')
                r = requests.get(img_full_url)
                # 检查请求是否成功
                r.raise_for_status()
                # wb表示写入二进制文件,使用r.content方式响应二进制内容
                with open(path, "wb") as f:
                    f.write(r.content)
                print('爬取完成')
            else:
                print('图片已经存在')
        except Exception as e:
            print('爬取失败:' + str(e))
            break
发布了45 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24542767/article/details/103505580