搜尋
首頁後端開發Python教學入門級 Bing 壁紙刮刀

Entry-Level Bing Wallpaper Scraper

準備工作

Bing 桌布網頁元素與 API 分析
要使用 Bing 建立自動桌布下載器,我們需要了解如何與 Bing API 互動。目標是獲取壁紙 URL 並將其以所需格式保存在本地。我們還將探索相關的 API、圖像元素和 URL 模式。

關鍵部件:

1。 Bing 的桌布 API:
Bing 提供了一個端點來存取其壁紙元數據,包括圖像 URL、標題和描述。我們使用的主要終點是:

https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US

  • idx=0: 壁紙索引(從今天開始)。
  • n=1:要取得的壁紙數量(在本例中,只有一張)。
  • mkt=en-US:市場/語言代碼(在本例中為英語 - 美國)。

2。圖片網址及下載:
API 提供的圖像 URL 通常採用相對格式(以 /th?id=... 開頭)。要下載圖像,我們需要在前面添加基本 URL https://www.bing.com。

格式和命名約定:

圖片 URL 通常採用以下形式:

/th?id=OHR.SouthPadre_ZH-CN8788572569_1920x1080.jpg

我們將對其進行處理以提取必要的信息,例如圖像名稱和檔案副檔名,並相應地保存。

過程

1。從 Bing API 取得資料:
第一步是向 Bing API 發送 GET 請求。這將返回一個 JSON 對象,其中包含給定日期的壁紙的元資料。

import requests
import os

# Simulate browser request headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
}

# Directory to save wallpapers
default_pictures_dir = os.path.join(os.path.expanduser("~"), "Pictures")
picture_path = os.path.join(default_pictures_dir, "bing")

# Create the directory if it doesn't exist
if not os.path.exists(picture_path):
    os.makedirs(picture_path)

# Fetch wallpapers (last 4 days including today)
for idx in range(4):
    # Request Bing's wallpaper metadata
    api_url = f"https://www.bing.com/HPImageArchive.aspx?format=js&idx={idx}&n=1&mkt=en-US"
    response = requests.get(api_url, headers=headers)
    if response.status_code != 200:
        print(f"Failed to fetch data for idx={idx}, skipping.")
        continue

    data = response.json()
    if not data.get("images"):
        print(f"No images found for idx={idx}, skipping.")
        continue

    # Extract image details
    image_info = data["images"][0]
    image_url = "https://www.bing.com" + image_info["url"]
    image_name = image_info["urlbase"].split("/")[-1] + ".jpg"
    save_path = os.path.join(picture_path, image_name)

    # Download the image
    image_response = requests.get(image_url, headers=headers)
    if image_response.status_code == 200:
        with open(save_path, "wb") as f:
            f.write(image_response.content)
        print(f"Downloaded: {save_path}")
    else:
        print(f"Failed to download image for idx={idx}.")

線上測驗

python3 -c "$(curl -fsSL https://ghproxy.com/https://raw.githubusercontent.com/Excalibra/scripts/refs/heads/main/d-python/get_bing_wallpapers.py)"

以上是入門級 Bing 壁紙刮刀的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何將元素附加到Python數組?您如何將元素附加到Python數組?Apr 30, 2025 am 12:19 AM

Inpython,YouAppendElementStoAlistusingTheAppend()方法。 1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware

您如何調試與Shebang有關的問題?您如何調試與Shebang有關的問題?Apr 30, 2025 am 12:17 AM

調試shebang問題的方法包括:1.檢查shebang行確保是腳本首行且無前置空格;2.驗證解釋器路徑是否正確;3.直接調用解釋器運行腳本以隔離shebang問題;4.使用strace或truss跟踪系統調用;5.檢查環境變量對shebang的影響。

如何從python數組中刪除元素?如何從python數組中刪除元素?Apr 30, 2025 am 12:16 AM

pythonlistscanbemanipulationusseveralmethodstoremovelements:1)theremove()MethodRemovestHefirStocCurrenceOfAstePecificiedValue.2)thepop()thepop()methodRemovesandReturnturnturnturnsanaNelementAgivenIndex.3)

可以在Python列表中存儲哪些數據類型?可以在Python列表中存儲哪些數據類型?Apr 30, 2025 am 12:07 AM

pythonlistscanstoreanydatate型,包括素,弦,浮子,布爾人,其他列表和迪克尼亞式

在Python列表上可以執行哪些常見操作?在Python列表上可以執行哪些常見操作?Apr 30, 2025 am 12:01 AM

pythristssupportnumeroferations:1)addingElementSwithAppend(),Extend(),andInsert()。 2)emovingItemSusingRemove(),pop(),andclear(),and clear()。 3)訪問andModifyingandmodifyingwithIndexingandSlicing.4)

如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境