import requests
import os
url = "https://wx4.sinaimg.cn/mw690/005Ed7hGgy1gcra7kbkuej30eg0eg41r.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("爬取失败")
‘wb’,'rb’代表二进制读写
UTF-8编码读写:
f = open(‘E:\python\python\gbk.txt’, ‘r’, encoding=‘gbk’)