Python 爬虫-图片的爬取
2017-07-25 22:49:21
import requests import os url = \'https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-278989.jpg\' root = \'E://pics//\' path = root + url.split(\'/\')[-1] def gethtml(url): # 打开网页有风险,需要使用try-except语句进行风险控制 kv = {\'user-agent\':\'Chrome/10\'} try: r = requests.get(url,headers=kv) r.raise_for_status() # 如果打开失败,则会抛出一个HttpError异常 # encoding是从header中分析出来的编码方式,apparent_encoding是 从内容分析出的编码方式 #r.encoding=r.apparent_encoding return r.content except: print("打开失败") if __name__ ==\'__main__\': if not os.path.exists(root): os.mkdir(root) r = gethtml(url) with open(path,\'wb\') as f: f.write(r) f.close() print(\'图片已存储\')