import urllib.request import json import os #Import OS module import requests #Import requests module class BeautifulPicture(): def __init__(self): #Class initialization operations self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} #Specify a request header for the request to simulate the Chrome browser. self.folder_path = 'D:\demo\BeautifulPicture' #Set the file directory to which pictures are to be stored. #Using urllib2 to get network data def registerUrl(self): print('Start creating folders') self.mkdir(self.folder_path) #create folder print('Start switching folder') os.chdir(self.folder_path) #Switch path to the above created try:
# Requested interfaceURL="https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=0%2C0&fp=detail&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=0&lpn=0&st=undefined&word=%E6%A0%A1%E8%8A%B1&z=0&ic=undefined&s=undefined&se=&tab=0&width=undefined&height=undefined&face=undefined&istype=0&qc=&nc=&fr=&simics=&srctype=&bdtype=0&rpstart=0&rpnum=0&cs=3447792407%2C2312708615&catename=&cardserver=&tabname=&pn=0&rn=30&gsm=0&1535795026719=" data = urllib.request.urlopen(url).read() return data except Exception as e: print(e) #write file def save_img(self, url, name): ##Save the picture print(url) img = self.request(url) file_name = name + '.jpg' print('Start saving pictures.') with open(file_name, 'ab') as f: f.write(img.content) # print(file_name,'Picture saved successfully! ') #Parsing JSON data obtained from the network def praserJsonFile(self, jsonData): value = json.loads(jsonData) data = value['data'] print(data) for i in data: url = i['middleURL'] name = i['fromPageTitleEnc'] self.save_img(url, name) def request(self, url): #Return to web page response r = requests.get(url, headers=self.headers) # Like the target URL address sends the get request, returns a response object. Any headers parameters are OK. return r def mkdir(self, path): ##This function creates folders. path = path.strip() isExists = os.path.exists(path) if not isExists: print('Create name is called', path, 'Folders') os.makedirs(path) print('Create success!') else: print(path, 'Folder already exists, no longer created') if __name__ == "__main__": beauty = BeautifulPicture() #Creating instances of classes data = beauty.registerUrl() # jsonFile(data) beauty.praserJsonFile(data)