python脚本-下载当日bing的壁纸

代码比较简单,功能是实现从bing下载当日的壁纸,程序最后会在py文件同级目录下新建bing文件夹,并把壁纸存放到该文件夹内,代码如下:

使用AI生成的代码,实测可行:

import requests
import os

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

    # Send a GET request to the Bing image API
    response = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")

    # Check if the request was successful
    if response.status_code == 200:
        # Get the URL of the image from the response
        image_url = response.json()["images"][0]["url"]

        # Download the image and save it to the specified directory
        image_data = requests.get("https://www.bing.com" + image_url).content
        with open(os.path.join(directory, "bing_image.jpg"), "wb") as f:
            f.write(image_data)
        
        print("Image saved successfully!")
    else:
        print("Failed to retrieve image from Bing.")

# Specify the directory where the image should be saved
directory = "image"

# Call the function to save the Bing image
save_bing_images(directory)

自己实现的代码:

# -*- coding:utf-8 -*-
__author__ = 'ppdyhappy'

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.disable(logging.DEBUG)
import requests
import os
import bs4
import re

# g_img={url: "/az/hprichbg/rb/OakTreeMaize_ZH-CN10523296117_1920x1080.jpg",id:'bgDiv',d:'200',cN:'_SS',crN:'bIm',hash: "118",del: 50}
BG_IMAGE_URL_FLAG = 'g_img='

def get_bing_bg():
    os.chdir('.')

    imageUrlRegex = re.compile(r'g_img={url:\s*"(.+jpg)"')

    webPath = r'https://cn.bing.com/'

    if not os.path.isdir('bing'):
        os.makedirs('bing')

    res = requests.get(webPath)
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, "html5lib")
    elems = soup.select('script[type="text/rms"]')

    logging.debug(len(elems))

    cnt = 0
    while cnt < len(elems):
        elemText = elems[cnt].getText()
        if BG_IMAGE_URL_FLAG in elemText:
            # logging.debug(elemText)
            imageUrlRegexResult = imageUrlRegex.search(elemText)
            imageUrl = webPath + imageUrlRegexResult.group(1)[1:]
            break
        cnt += 1

    logging.info(imageUrl)

    res = requests.get(imageUrl)
    res.raise_for_status()

    imageFile = open(os.path.join('bing', os.path.basename(imageUrl)), 'wb')
    for chunk in res.iter_content(100000):
        imageFile.write(chunk)
    imageFile.close()

    logging.debug('done')

if __name__ == '__main__':
    get_bing_bg()

需要安装第三方模块,使用pip进行下载

pip install requests

pip install beautifulsoup4

安装HTML解析器

pip install html5lib

参考链接:Beautiful Soup 4.2.0 文档 — Beautiful Soup 4.2.0 documentation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值