自学python之获取bing每日图片

来源:互联网 发布:淘宝皇冠店铺多少钱 编辑:程序博客网 时间:2024/05/01 20:03

博主有一自己的网站,苦于没有合适的图片作为背景,刚刚开始自学python,寻思着能不能用python把bing的每日图片弄下来作为背景。

Bing给我们提供了一个每日一图的开放api:http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1(n代表要获得几组图片信息,我这边设为1)

我们在这里能够得到一个xml风格的string,所以有两种思路。

一是用正则表达式提取url:

"""A simple script to import the daily picture of bing"""import urllib.requestimport reimport timedef 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 = urllib.request.Request(hostname)    webpage = urllib.request.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.request.urlretrieve(url, pic_file_name+url[-4:])if __name__ == '__main__':    main()
二是将string转换为xml对象,对xml节点进行提取,较一来说更为规范:

"""A simple script to import the daily picture of bing"""import urllib.requestimport xml.etree.ElementTree as ETimport timedef 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()



0 0