python获取bing上的壁纸

本文介绍了一种使用Python脚本从必应网站自动抓取每日背景图片的方法。通过调用必应提供的XML API,该脚本能够解析图片链接并下载到本地,文件名采用当前日期格式。

vi bing_pictures.py


"""A simple script to import the daily picture of bing"""

import urllib
import urllib2
import urllib3
import re
import time

def main():
        """We use the xml api provided by bing to get the pic url"""
        hostname = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1"
        req = urllib2.Request(hostname)
        webpage = urllib2.urlopen(req)
        content = str(webpage.read())
        url_tail = re.search(r'<url>[^\s]*</url>', content)
        url = 'http://cn.bing.com' + str(url_tail.group())[5:-6]
        print(url)
        pic_file_name = time.strftime('%Y_%m_%d', time.localtime(time.time()))
        urllib.urlretrieve(url, pic_file_name+url[-4:])

if __name__ == '__main__':
        main()


vi bing_xml_pictures.py


"""A simple script to import the daily picture of bing"""
import urllib.request
import xml.etree.ElementTree as ET
import time

def main():
    """We use the xml api provided by bing to get the pic url"""
    req = urllib.request.Request("http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1")
    webpage = urllib.request.urlopen(req)
    root = ET.fromstring(webpage.read())
    url = 'http://cn.bing.com'+root.find('image').find('url').text
    print(url)
    pic_file_name = time.strftime('%Y_%m_%d', time.localtime(time.time()))+\
        root.find('image').find('messages').find('message').find('msgtext').text
    urllib.request.urlretrieve(url, pic_file_name+url[-4:])

if __name__ == '__main__':
    main()

python bing_pictures.py bing_xml_pictures.py


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值