以下爬取的是网易云视频
1.首先需要安装requests
在cmd中,使用如下指令安装requests:
pip install requests
或者:
easy_install requests
用法:
2.直接看代码
import requests
import os
url="http://flv3.bn.netease.com/videolib1/1808/15/WbBho069W/SD/WbBho069W-mobile.mp4"
root = "D://pics//"
path = root+url.split('/')[-1]#获得一个url最后一个/后的字符串
try:
if not os.path.exists(root):#测试指定文件是否存在
os.mkdir(root)#创建目录(创建一级目录)
print("aaa")
if not os.path.exists(path):#查看视频是否存在
r = requests.get(url)
r.raise_for_status()
"""
r.raise_for_status()解释:
https://blog.csdn.net/kangyan__/article/details/78506243
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。
"""
with open(path,'wb') as f:# 读写文件
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件保存成功")
except:
print("爬取失败")