用Python写一个爬取网页图片的代码
以下是使用Python爬取网页图片的示例代码:
import requests
import os
from bs4 import BeautifulSoup
# 网页地址
url = 'https://www.example.com'
# 发送请求获取网页内容
response = requests.get(url)
# 解析网页内容
soup = BeautifulSoup(response.content, 'html.parser')
# 查找网页中所有的图片标签
img_tags = soup.find_all('img')
# 创建保存图片的文件夹
if not os.path.exists('images'):
os.makedirs('images')
# 下载图片到本地
for img_tag in img_tags:
img_url = img_tag.get('src')
if img_url:
img_name = img_url.split('/')[-1]
img_path = os.path.join('images', img_name)
img_response = requests.get(img_url)
with open(img_path, 'wb') as f:
f.write(img_response.content)
print(f'Download {img_url} to {img_path} success!')
该代码会爬取指定网页中所有的图片,并下载到本地的images文件夹中。需要注意的是,该代码只能爬取网页中直接引用的图片,无法爬取使用JavaScript或CSS生成的图片。
原文地址: https://www.cveoy.top/t/topic/G0Z 著作权归作者所有。请勿转载和采集!