from bs4 import BeautifulSoup
import requests as req
使用BeautifulSoup4下载网页上所有图片
# 新建一个计数器
i = 0
# 遍历所有的图片
for ele in soup.find_all("img"):
# 检查图片是否为网络图片
if ele["src"].startswith("https") or ele["src"].startswith("http"):
# 获取图片内容
r = req.get(ele["src"])
# 定义本地储存文件名称,此处定义为 image#数字.png
filename = "image#" + str(i) + ".png"
# 打开文件
with open(filename, "wb") as file:
# 写入文件
file.write(r.content)
# 计数器 + 1
i += 1