Python 图片爬虫实战:如何使用代码从网页获取图片并保存到本地
这段代码可以用来爬取网页中的图片,并将其保存到本地文件夹中。你可以将其用作图片爬虫,或者作为学习 Python 爬虫的练习案例。
使用方法:
- 将代码复制到 Python 环境中(如 Anaconda、Jupyter Notebook 等)
- 修改 'url' 变量为你要爬取的网页链接
- 修改 'folder_path' 变量为你要保存图片的文件夹路径
- 运行代码
代码将会自动爬取网页中的所有图片,并将其保存到指定的文件夹中。
import requests
from bs4 import BeautifulSoup
import os
# 网页链接
url = 'https://www.example.com'
# 获取网页内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有图片标签
img_tags = soup.find_all('img')
# 创建文件夹(如果不存在)
folder_path = 'D:/pt'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# 遍历所有图片标签,获取图片 URL,并保存到本地
for img in img_tags:
img_url = img.get('src')
if img_url and 'http' in img_url:
file_name = img_url.split('/')[-1]
file_path = os.path.join(folder_path, file_name)
img_data = requests.get(img_url).content
with open(file_path, 'wb') as f:
f.write(img_data)
原文地址: https://www.cveoy.top/t/topic/n2Z0 著作权归作者所有。请勿转载和采集!