import os
import requests
from bs4 import BeautifulSoup
import re
# 目标网页URL
url = '
https://example.com'
# 发送GET请求获取网页内容
response = requests.get(url)
# 使用Beautiful Soup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 使用正则表达式提取图片URL
img_tags = soup.find_all('img')
img_urls = [img['src'] for img in img_tags if 'src' in img.attrs]
# 下载图片
for img_url in img_urls:
# 检查图片URL是否是完整的URL,如果不是,构建完整的URL
if not img_url.startswith('http'):
img_url = url + img_url
# 获取图片文件名
img_filename = os.path.basename(img_url)
# 发送GET请求下载图片
img_response = requests.get(img_url)
# 保存图片到本地
with open(img_filename, 'wb') as img_file:
img_file.write(img_response.content)
print(f'下载图片:{img_filename}')
print('图片下载完成!')