简短的爬虫程序,14行Python代码轻松实现爬取网站视频
import requests
from bs4 import BeautifulSoup
import re
# 视频下载函数
def download_video(url, filename):
response = requests.get(url, stream=True)
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print(f"视频 {filename} 已保存。")
# 主函数
def main(url):
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
video_tags = soup.find_all('source')
video_urls = for video in video_tags]
video_urls = [re.sub(r'\\', '', url) for url in video_urls] # 处理Windows路径问题
for url in video_urls:
filename = url.split('/')[-1]
download_video(url, filename)
# 使用方法: 网页url
main('http://www.example.com/videos')
这段代码使用了requests库来发送HTTP请求,BeautifulSoup来解析HTML,以及re库来处理正则表达式。代码中的download_video
函数负责实际下载视频,而main
函数负责提取视频链接并调用download_video
函数进行下载。使用时只需要将'http://www.example.com/videos'替换为目标网页的URL。
评论已关闭