python3下载必应的图片

本文介绍如何利用Python3抓取必应搜索引擎首页的每日更换壁纸,并将其保存到本地,文件名设定为当前日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  必应搜索的网址为:https://cn.bing.com/,该网站的背景图片会每日更新,使用python3获取该网站的html源码,解析出背景图片,保存到指定目录,并重命名为当前日期。

#!/usr/bin/python3
# get the picture from Bing
import re
import requests
import datetime

url = 'https://cn.bing.com/'
# directory to save the picture
dir = 'C:\\Users\\Liangjin\\Pictures\\Saved Pictures\\'

# get the source code of the web page
html = requests.get(url).text
# parse out the picture name
Nurl = re.findall('id="bgLink" rel="preload" href="(.*?)&', html, re.S)
for name in Nurl:
    # the full path of the remote picture
    picture = url + name
    print(picture)
    # save the picture
    pic = requests.get(picture)
    file = dir + str(datetime.datetime.now().year)+'-'+str(
        datetime.datetime.now().month)+'-'+str(datetime.datetime.now().day) + '.jpg'
    fp = open(file, 'wb')
    fp.write(pic.content)
    fp.close()

要使用Python 3来批量下载Bing搜索的图片,可以按照以下步骤进行: 1. 首先,需要安装requests和beautifulsoup4这两个库。可以使用以下命令安装它们: ``` pip install requests pip install beautifulsoup4 ``` 2. 导入所需的模块: ```python import requests from bs4 import BeautifulSoup import os ``` 3. 创建一个函数来下载图片: ```python def download_image(url, save_dir): filename = os.path.join(save_dir, url.split('/')[-1]) response = requests.get(url, stream=True) if response.status_code == 200: with open(filename, 'wb') as file: file.write(response.content) print('成功下载图片:', filename) else: print('无法下载图片:', url) ``` 4. 定义一个函数来搜索并批量下载图片: ```python def download_images(query, save_dir, num_images): search_url = 'https://www.bing.com/images/search?q=' + query response = requests.get(search_url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') image_tags = soup.find_all('img') count = 0 for image_tag in image_tags: image_url = image_tag['src'] if image_url.startswith('https://'): download_image(image_url, save_dir) count += 1 if count == num_images: break else: print('搜索失败') ``` 5. 调用download_images函数并指定搜索的关键字、保存目录以及要下载图片数量: ```python query = '美食' # 搜索关键字 save_dir = 'images' # 图片保存目录 num_images = 10 # 要下载图片数量 download_images(query, save_dir, num_images) ``` 运行脚本后,将会在指定目录下下载指定数量的Bing搜索结果中的图片。 需要注意的是,根据Bing的使用条款,禁止使用非官方API进行批量下载图片。因此,在使用此方式之前,请确保你已阅读并遵守相关使用条款。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值