python3必應壁紙爬蟲練手

修復一個必應壁紙下載工具
資源站和之前同學一樣, bing.ioliu.cn
打包好可以直接運行的版本在鏈接裏
主要是練手 有機會再做更新了:)

老規矩,
先pip install 這幾個第三方庫

import re
import os
import requests
from time import sleep

全部源碼如下:

import re
import os
import requests
from time import sleep

headers = {
    "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) "
                   "Gecko/20100101 Firefox/64.0")
}

def get_index(resolution, index=1):
    url = f"https://bing.ioliu.cn/ranking?p={index}"
    res = requests.get(url, headers=headers)
    urls = re.findall('pic=(.*?)\\.jpg', res.text)
    _old_resolution = urls[1].split("_")[-1]
    return {url.split("/")[-1].replace(_old_resolution, resolution): url.replace(_old_resolution, resolution) + ".jpg"
            for url in urls}

def download_pic(pics):
    if os.path.exists('必應壁紙'):
        pass
    else:
        os.mkdir('必應壁紙')
        print('目錄創建成功')
    try:
        for pic_name, pic_url in pics.items():
            res = requests.get(pic_url, headers=headers)
            with open(f"必應壁紙\\{pic_name}.jpg", mode="wb") as f:
                f.write(res.content)
            print(f"{pic_name} 下載完成")
    except Exception as e:
        print("下載出錯", e)

def input_index():
    print("必應壁紙下載工具, 本工具未經資源站授權.")
    print("僅做學習和交流之用, 隨時有可能停止維護.")
    print("目前資源站收容頁數爲87,當前僅提供1920x1080分辨率下載")
    while True:
        sleep(0.1)
        index = input("請輸入要下載的頁數(Max=87):")
        try:
            if index == "Q":
                exit()
            index = 87 if int(index) > 87 else int(index)
            return index
        except ValueError:
            print("請輸入數字, 或輸入Q退出!")

def main():
    index = input_index()
    i = 1
    while i <= index:
        print(f"當前第{i}頁,共需要下載{index}頁")
        pics = get_index("1920x1080", i)
        download_pic(pics)
        i += 1
    print("下載完成,將在3秒後關閉...")
    sleep(1)
    print("2")
    sleep(1)
    print("1")
    sleep(1)
    print("0")

if __name__ == '__main__':
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章