1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import requests import json import random import shutil """ Download pictures from bing.com
1、Request home page for picture list 2、Get a picture randomly and download it """ host = 'http://www.bing.com' index = random.randint(0, 7) base_url = host + '/HPImageArchive.aspx?idx=' + str(index) + '&n=5&format=js' header = { 'header': "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/54.0.2840.71 Safari/537.36 " } # 1. request home page for picture list response = requests.get(base_url, headers=header).text images = json.loads(response)['images'] i = random.randint(0, len(images) - 1) url = host + images[i]['urlbase'] + '_UHD.jpg' file_name = images[i]['urlbase'].split('=')[1].split('_')[0] + '.jpg' # 2. get a picture randomly and download it response = requests.get(url, stream=True) with open(file_name, 'wb') as out: shutil.copyfileobj(response.raw, out) del response
|