Python 爬虫实战:轻松获取二次元电脑壁纸
以下是一个简单的 Python 爬虫代码,可以用于爬取二次元电脑壁纸并保存到本地:
import requests
import os
# 设置下载图片保存路径
save_path = './二次元壁纸/'
# 创建文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 请求地址
url = 'https://www.acgwallpaper.net/category/sort-views/'
# 发送请求
response = requests.get(url, headers=headers)
# 解析响应
html = response.content.decode('utf-8')
start_index = html.find('<div class="container box-padded">')
end_index = html.find('<div class="col-md-4 col-sm-6 col-xs-12 text-center">')
html = html[start_index:end_index]
# 解析图片地址
img_urls = []
start_index = 0
while True:
start_index = html.find('<img src='', start_index)
if start_index == -1:
break
end_index = html.find(''', start_index + 10)
img_url = html[start_index + 10:end_index]
img_urls.append(img_url)
start_index = end_index
# 下载图片
for url in img_urls:
# 获取图片名
img_name = url.split('/')[-1]
# 拼接保存路径
img_path = os.path.join(save_path, img_name)
# 发送请求并保存图片
response = requests.get(url, headers=headers)
with open(img_path, 'wb') as f:
f.write(response.content)
print('保存图片成功:', img_path)
该爬虫代码使用了 requests 库进行网络请求,使用 os 库创建文件夹和拼接文件路径,使用字符串操作解析 html 响应中的图片地址,并使用 requests 库下载图片并保存到本地。需要注意的是,该代码仅供学习参考,请勿用于商业用途。
原文地址: https://www.cveoy.top/t/topic/nhud 著作权归作者所有。请勿转载和采集!