第一个爬虫小程序
要求:从网上爬取一张图片保存到本地的上
import requestsimport osurl = "http://p1.so.qhimgs1.com/bdr/200_200_/t01838143cb2c95c22d.jpg"root = "/home/python/Desktop/"path = root + url.split("/")[-1]try: # 判断文件是否存在 if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(url) # 判断网络连接的状态 r.raise_for_status() #使用with语句可以不用自己手动关闭已经打开的文件流 with open(p ,"wb") as f: # 返回的是bytes型也就是二进制的数据 f.write(r.content) print("爬取完成") else: print("文件已存在")except Exception as e: print("爬取失败:"+str(e))小程序













