元气桌面静态壁纸下载器 V1.0

查看 106|回复 11
作者:koogg   
找壁纸的时候遇到元气桌面壁纸,有些壁纸看起来不错,但是网页不给下载,于是使用python抓取了一下网页,发现在网页源文件就有,只是动态壁纸的分辨率太低,就留下静态壁纸了,
工具支持单个下载,分类下载,以及全部下载。 考虑到有人没有编译环境附件给了编译后的exe文件可直接使用。 因为是chatgpt写的,所以有不清楚的地方可以直接发给它咨询
[Python] 纯文本查看 复制代码import tkinter as tk
from tkinter import messagebox
from concurrent.futures import ThreadPoolExecutor
import requests
import os
import random
from bs4 import BeautifulSoup
import threading
# 创建图片存储文件夹
os.makedirs('imgs', exist_ok=True)
def get_random_user_agent():
    user_agents = [
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
        "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
    ]
    return random.choice(user_agents)
def download_image(img_url, img_title, category):
    try:
        headers = {'User-Agent': get_random_user_agent()}
        img_resp = requests.get(img_url, headers=headers)
        if img_resp.status_code == 200:
            valid_img_title = "".join(c for c in img_title if c.isalnum() or c in (' ', '.', '_')).rstrip()
            category_path = os.path.join('imgs', category)  # Create category path
            os.makedirs(category_path, exist_ok=True)  # Create category folder
            img_path = os.path.join(category_path, f"{valid_img_title}.jpg")
            counter = 1
            base_img_path, ext = os.path.splitext(img_path)
            while os.path.exists(img_path):
                img_path = f"{base_img_path}_{counter}{ext}"
                counter += 1
            with open(img_path, 'wb') as f:
                f.write(img_resp.content)
            print(f"Downloaded: {img_title} as {img_path}")
        else:
            print(f"Failed to download {img_title}")
    except Exception as e:
        print(f"Error downloading {img_title}: {e}")
def download_single_wallpaper(url):
    try:
        headers = {'User-Agent': get_random_user_agent()}
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'lxml')
        img_div = soup.find('div', class_='relative mb-3 float-left')
        img_tag = img_div.find('img')
        img_title = img_tag.get('alt')
        img_url = img_tag.get('src')
        # Here we need to determine the category for the single wallpaper
        category = "单张"  # You can replace this with a relevant category if applicable
        download_image(img_url, img_title, category)
        messagebox.showinfo("完成", f"单张壁纸 {img_title} 下载完成!")
    except Exception as e:
        print(f"Error downloading single wallpaper: {e}")
        messagebox.showerror("错误", f"下载失败:{e}")
def start_single_download_thread():
    url = entry_single_url.get().strip()
    if not url:
        messagebox.showwarning("警告", "请输入有效的壁纸链接!")
        return
    threading.Thread(target=download_single_wallpaper, args=(url,)).start()
def scrape_page(page, sort):
    url = f'https://bizhi.cheetahfun.com/dn/c{sort}j/p{page}'
    headers = {'User-Agent': get_random_user_agent()}
    print(f"Requesting URL: {url}")
    try:
        resp = requests.get(url, headers=headers)
        if resp.status_code == 404:
            print(f"Page {page} not found. Stopping.")
            return False
        soup = BeautifulSoup(resp.text, 'html.parser')
        img_divs = soup.find_all('div', class_='overflow-hidden relative rounded-sm w-79 mx-1 mb-3 h-40')
        img_urls = []
        for img_div in img_divs:
            img_url = img_div.find('a').get('href')
            img_title = img_div.find('a').get('title')
            resp_child = requests.get(img_url, headers=headers)
            soup_child = BeautifulSoup(resp_child.text, 'html.parser')
            img_list_child = soup_child.find_all('div', class_='relative mb-3 float-left')
            # Get the category from sort_mapping based on sort value
            category = [key for key, value in sort_mapping.items() if value == sort][0]
            img_urls.extend(
                (img_child.find('img').get('src'), img_child.find('img').get('alt'), category)
                for img_child in img_list_child
            )
        with ThreadPoolExecutor(max_workers=5) as executor:
            executor.map(lambda img: download_image(img[0], img[1], img[2]), img_urls)  # Pass category
    except Exception as e:
        print(f"Error scraping page {page}: {e}")
    return True
def start_download(sort_values, start_page, end_page, download_all_pages):
    loading_label.pack()
    for sort in sort_values:
        page = start_page
        while True:
            if not scrape_page(page, sort):
                break
            if not download_all_pages and page >= end_page:
                break
            page += 1
    loading_label.pack_forget()
    messagebox.showinfo("完成", "下载完成!")
def start_download_thread():
    sort_values = [sort_mapping[label] for label, var in sort_vars.items() if var.get()]
    if not sort_values:
        messagebox.showwarning("警告", "请选择至少一个分类!")
        return
    try:
        start_page = 1
        end_page = None
        if not var_all_pages.get():
            start_page = int(entry_start_page.get())
            end_page = int(entry_end_page.get())
            if start_page


PixPin_2024-10-29_08-38-44.png (26.69 KB, 下载次数: 0)
下载附件
2024-10-29 08:38 上传

壁纸网址就在代码里面,就不贴出来了,因为分类全部下载会很占用资源,建议按需下载。
编译后文件下载地址:
https://koogg.lanzout.com/b0r9mz1xi
密码:7bsj

壁纸, 请输入

koogg
OP
  


hw8831 发表于 2024-10-29 11:48
楼主可以做一个360桌面壁纸下载器吗?我电脑上的用的360桌面壁纸,感觉好多好看的!

因为我不使用360的东西,我网上找了个所谓的360壁纸接口,你可以试试分类下载看看,能不能满足你的需求
[Python] 纯文本查看 复制代码import requests
import os
import threading
import tkinter as tk
from tkinter import messagebox
# Mapping of category names to IDs
categories = {
    1: "每日精选",
    5: "游戏",
    6: "美女",
    9: "风景",
    10: "视觉创意",
    11: "明星影视",
    12: "汽车",
    14: "萌宠动物",
    15: "小清新",
    16: "体育",
    22: "军事",
    26: "动漫卡通",
    30: "情感",
    35: "文字",
}
def get_images(category_id, start, count):
    url = f"http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByCategory&cid={category_id}&start={start}&count={count}"
    response = requests.get(url)
    print(f"Fetching images from: {url}")  # Debug log
    if response.status_code == 200:
        data = response.json()
        if data["errno"] == "0":
            print(f"Found {len(data['data'])} images for category {category_id}.")  # Debug log
            return [(item["id"], item["url"]) for item in data["data"]]
        else:
            print(f"Error from API: {data['errmsg']}")  # Debug log
    else:
        print(f"Failed to fetch data: {response.status_code}")  # Debug log
    return []
def download_image(url, folder, img_id):
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            os.makedirs(folder, exist_ok=True)
            filename = os.path.join(folder, f"{img_id}.jpg")
            with open(filename, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)
            print(f"Downloaded: {filename}")  # Debug log
        else:
            print(f"Failed to download image: {url} (status code: {response.status_code})")  # Debug log
    except Exception as e:
        print(f"Error downloading {url}: {e}")  # Debug log
def download_images(selected_categories, start, count):
    threads = []
    base_folder = 'imgs'  # Base folder for all images
    for category_id in selected_categories:
        category_name = categories[category_id]
        category_folder = os.path.join(base_folder, category_name)  # Create folder for each category
        images = get_images(category_id, start, count)
        if not images:
            print(f"No images found for category {category_id}.")  # Debug log
        for img_id, img_url in images:
            thread = threading.Thread(target=download_image, args=(img_url, category_folder, img_id))
            thread.start()
            threads.append(thread)
    for thread in threads:
        thread.join()
    download_label.config(text="")  # Clear the downloading message
    messagebox.showinfo("完成", "所有图片已下载!")
def start_download():
    try:
        selected_categories = [key for key, var in category_vars.items() if var.get()]
        start = int(entry_start.get())
        count = int(entry_count.get())
        if selected_categories:
            download_label.config(text="正在下载...")
            root.update()  # Update the GUI to show the status message
            download_images(selected_categories, start, count)
        else:
            messagebox.showerror("错误", "请至少选择一个分类。")
    except ValueError:
        messagebox.showerror("错误", "请输入有效的数字。")
# GUI Setup
root = tk.Tk()
root.title("360壁纸分类下载器V1.0")
root.geometry("300x400")
tk.Label(root, text="请选择需要下载的壁纸分类:", font=("Arial", 14)).grid(row=0, columnspan=2, sticky='nsew')
# Create a frame for the checkboxes to organize them
checkbox_frame = tk.Frame(root)
checkbox_frame.grid(row=1, column=0, columnspan=2, sticky='nsew')
# Create checkboxes for each category, arranged in two columns
category_vars = {}
for idx, (key, name) in enumerate(categories.items()):
    var = tk.BooleanVar()
    category_vars[key] = var
    col = idx % 2  # Determine column (0 or 1)
    row = idx // 2  # Determine row (starting from 0)
    tk.Checkbutton(checkbox_frame, text=name, variable=var).grid(row=row, column=col, sticky='w')
# Adjusting labels and entries for start and count
tk.Label(root, text="从第几个开始下载 (start):").grid(row=len(categories) // 2 + 2, column=0, sticky='e')
entry_start = tk.Entry(root)
entry_start.grid(row=len(categories) // 2 + 2, column=1)
tk.Label(root, text="需要下载的数量 (count):").grid(row=len(categories) // 2 + 3, column=0, sticky='e')
entry_count = tk.Entry(root)
entry_count.grid(row=len(categories) // 2 + 3, column=1)
download_label = tk.Label(root, text="")
download_label.grid(row=len(categories) // 2 + 4, columnspan=2, sticky='nsew')
tk.Button(root, text="开始下载", command=start_download).grid(row=len(categories) // 2 + 5, columnspan=2, sticky='nsew')
# Configure grid weights for proper centering
for i in range(len(categories) // 2 + 6):
    root.grid_rowconfigure(i, weight=1)
    root.grid_columnconfigure(0, weight=1)
    root.grid_columnconfigure(1, weight=1)
root.mainloop()
我也打包了一个exe文件,你可以试试,下载地址在帖子的目录里面了
http88   

https://bizhi.cheetahfun.com/dtag_109_a14fdede25965c8c0bd3ceb11f364baf/   下载了,有上万张高清壁纸,太多了,眼花缭乱。
changyufeichang   

好东西,下载下来研究下,感谢
醉生梦死.   

非常实用且不错的一款工具,如果能分类储存则更完美了!期待下一个版本!感谢分享!
lp-cg   

感谢分享,收下了
JJ20160225   

学习学习!!!!看着不错
lishuichen   

收藏试用  感谢分享
tomliu   

看了源码, 思路不错, 还有图形化界面, 值得学习
haibovip   

感谢大佬分享。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部