Python爬虫实战:批量下载高清壁纸
import requests
from bs4 import BeautifulSoup
import os
def get_html():
for i in range(2, 20): # 获取第2到19页的图片
url = f'http://www.netbian.com/index_{i}.htm'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
images = soup.find_all('img') # 找到所有的图片标签
for image in images:
image_url = image['src'] # 获取图片的链接
if image_url.startswith('http'):
image_response = requests.get(image_url, headers=headers)
else:
image_response = requests.get('http://www.netbian.com/' + image_url, headers=headers)
# 创建目录
if not os.path.exists('images'):
os.makedirs('images')
# 保存图片
with open('images/' + image_url.split('/')[-1], 'wb') as f:
f.write(image_response.content)
get_html()
# 优化代码,增加容错处理
def get_html_optimized():
for i in range(2, 20): # 获取第2到19页的图片
try:
url = f'http://www.netbian.com/index_{i}.htm'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # 检查请求是否成功
soup = BeautifulSoup(response.content, 'html.parser')
images = soup.find_all('img') # 找到所有的图片标签
for image in images:
image_url = image['src'] # 获取图片的链接
if image_url.startswith('http'):
image_response = requests.get(image_url, headers=headers, timeout=10)
image_response.raise_for_status()
else:
image_response = requests.get('http://www.netbian.com/' + image_url, headers=headers, timeout=10)
image_response.raise_for_status()
# 创建目录
if not os.path.exists('images'):
os.makedirs('images')
# 保存图片
with open('images/' + image_url.split('/')[-1], 'wb') as f:
f.write(image_response.content)
except requests.exceptions.RequestException as e:
print(f'请求出错: {e}')
except Exception as e:
print(f'发生错误: {e}')
get_html_optimized()
代码说明:
- 导入库: 导入
requests用于发送HTTP请求,BeautifulSoup用于解析HTML,os用于文件操作。 get_html()函数:- 循环获取网页: 使用
for循环遍历目标网页的页码。 - 发送请求:使用
requests.get()发送HTTP请求获取网页内容。 - 解析HTML:使用
BeautifulSoup解析HTML,找到所有图片标签img。 - 获取图片链接:提取图片标签的
src属性,即图片链接。 - 下载图片:发送HTTP请求下载图片,并保存到本地。
- 循环获取网页: 使用
get_html_optimized()函数:- 在原函数基础上,增加了错误处理机制,使用
try...except捕获异常,提高代码健壮性。 - 使用
requests.exceptions.RequestException捕获网络请求异常。 - 使用
response.raise_for_status()检查HTTP请求状态码,确保请求成功。 - 设置请求超时时间
timeout=10,避免程序长时间等待无响应的请求。
- 在原函数基础上,增加了错误处理机制,使用
使用方法:
- 将代码保存为Python文件,例如
download_wallpaper.py - 在终端运行代码:
python download_wallpaper.py
注意事项:
- 爬取网页之前,请先阅读目标网站的 robots.txt 文件,遵守网站规则。
- 本代码仅供学习交流,请勿用于商业用途。
- 建议在下载图片时,设置合理的下载间隔,避免对目标网站造成过大压力。
希望本文能够帮助你使用Python爬虫技术批量下载高清壁纸!
原文地址: https://www.cveoy.top/t/topic/laiq 著作权归作者所有。请勿转载和采集!