编写python爬虫代码爬取blibli视频
时间: 2024-01-01 17:43:08 浏览: 47
好的,以下是爬取Bilibili视频的Python代码:
```python
import requests
import re
import os
# 设置请求头,模拟浏览器请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 获取视频页面的HTML代码
url = 'https://www.bilibili.com/video/BV1a4411B7cM'
response = requests.get(url, headers=headers).text
# 从HTML代码中获取视频的标题
title = re.findall('<title data-vue-meta="true">(.*?)_', response)[0]
print('视频标题为:', title)
# 从HTML代码中获取视频的播放地址
playurl = re.findall('"playurl":"(.*?)",', response)[0]
playurl = playurl.encode('utf-8').decode('unicode_escape')
# 下载视频到本地
try:
if not os.path.exists(title):
os.mkdir(title)
video = requests.get(playurl, headers=headers)
with open(title+'/'+title+'.mp4', 'wb') as f:
f.write(video.content)
print('视频下载完成!')
except:
print('视频下载失败!')
```
这段代码将会通过模拟浏览器请求获取Bilibili视频页面的HTML代码,然后通过正则表达式解析出视频的标题和播放地址,最后将视频下载到本地。请注意修改代码中的视频页面URL以及保存视频的路径。