python抓取bing主頁背景圖片

最初Python2寫法:
#!/usr/bin/env python

# -*- coding:utf-8 -*-html

# -*- author:nancy -*-python

# python2抓取bing主頁全部背景圖片正則表達式

import urllib,re,sys,osjson

def get_bing_backphoto():post

    if (os.path.exists('photos')== False):url

        os.mkdir('photos')spa

    for i in range(0,1000):.net

        url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)code

               +'&n=1&nc=1361089515117&FORM=HYLH1'orm

        html = urllib.urlopen(url).read()

        if html == 'null':

            print 'open & read bing error!'

            sys.exit(-1)

        reg = re.compile('"url":"(.*?)","urlbase"',re.S)

        text = re.findall(reg,html)

        #http://s.cn.bing.net/az/hprichbg/rb/LongJi_ZH-CN8658435963_1366x768.jpg

        for imgurl in text:

            right = imgurl.rindex('/')

            name = imgurl.replace(imgurl[:right+1],'')

            savepath = 'photos/'+ name

            urllib.urlretrieve(imgurl, savepath)

            print name + ' save success!'

get_bing_backphoto()

Python3與Python2的錯誤調整:
TypeError: can't use a string pattern on a bytes-like object
 緣由爲Python3 findall數據類型用bytes類型,所以在正則表達式前應添加html = html.decode('utf-8')。
 「AttributeError: 'module' object has no attribute 'urlopen'」
 緣由是Python3裏的urllib模塊已經發生改變,此處的urllib都應該改爲urllib.request。
因爲bing圖片對外接口的圖片json格式變了,python第三方庫的導入格式有變化,所以代碼調整以下:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# -*- author:nancy-*-

# python3抓取bing主頁全部背景圖片

import urllib.request,re,sys,os

def get_bing_backphoto():

    if (os.path.exists('photos')== False):

        os.mkdir('photos')

    for i in range(0,10):

        url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)+'&n=1&nc=1361089515117&FORM=HYLH1'

        html = urllib.request.urlopen(url).read()

        if html == 'null':

            print( 'open & read bing error!')

            sys.exit(-1)

        html = html.decode('utf-8')

        html = html.replace('/az/','http://s.cn.bing.net/az/')

        reg = re.compile('"url":"(.*?)","urlbase"',re.S)

        text = re.findall(reg,html)

        for imgurl in text :

            right = imgurl.rindex('/')

            print(imgurl)

            name = imgurl.replace(imgurl[:right+1],'')

            savepath = 'photos/'+ name

            urllib.request.urlretrieve(imgurl, savepath)

            print (name + ' save success!')

get_bing_backphoto()

轉載於:https://www.cnblogs.com/camilla/p/7144768.html