新手学习爬取图片
从中国大学MOOC学习心得
import requests
import os
url = "http://p2.so.qhimgs1.com/sdr/400__/t0100714605ba9621e2.jpg"
root = "G://picture//"
#目录路径
path = root + url.split('/')[-1]
'''url.split('/')[-1] 以“/”为界分割url最后一段得到t0100714605ba9621e2.jpg
root+url.split('/')[-1] 意思是连接两个字符串
'''
r = requests.get(url)
try:
if not os.path.exists(root):
'''os.path.exists(root) 判断目录root是否存在,存在,返回True
不存在,返回False。前面加个not,意思就是如果不存在执行后面代码
'''
os.mkdir(root)#创建目录(文件夹)
if not os.path.exists(path):
r=requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已经存在")
except:
print("爬取失败")