python网络图片爬取存储全代码

时间:2023-03-08 22:01:16
#图片爬取全代码
import requests
import os
url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1526377335903&di=" \
"804e31176babc6d47766261d0b02ca38&imgtype=0&src=http%3A%2F%2Fimg.mp." \
"sohu.com%2Fq_mini%2Cc_zoom%2Cw_640%2Fupload%2F20170810%2Fc25e385ca8e24cdb" \
"805a38ad5fcb52b9_th.jpg"
root = "D://pics//"
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)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失败")