【python】爬取4K壁纸保存到本地文件夹
import requests
from bs4 import BeautifulSoup
import os
# 图片保存路径
save_path = 'D:/Wallpapers'
# 创建保存文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 获取HTML内容
def get_html(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
except requests.RequestException:
return None
# 解析HTML获取图片链接
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
image_urls = [img['src'] for img in soup.find_all('img', class_='img-responsive')]
return image_urls
# 下载图片
def download_image(url, save_path):
response = requests.get(url)
if response.status_code == 200:
file_name = url.split('/')[-1]
with open(os.path.join(save_path, file_name), 'wb') as f:
f.write(response.content)
# 主函数
def main():
base_url = 'https://wall.alphacoders.com/by_category.php?id=14287&name=4K+Resolution'
html = get_html(base_url)
image_urls = parse_html(html)
for url in image_urls:
download_image(url, save_path)
print(f'Image saved: {url}')
if __name__ == '__main__':
main()
这段代码首先定义了图片保存的路径,并创建相应的文件夹(如果不存在的话)。然后定义了获取HTML内容、解析HTML获取图片链接、下载图片的函数。主函数main()组织这些函数的调用顺序,实现了从网页抓取图片并保存到本地的功能。
评论已关闭