'''
爬取校花網視頻
1.請求url
http://www.xiaohuar.com/v/
2.請求方式
GET
3.請求頭信息
User-Agent:用戶代理
'''
# 爬蟲三部曲
# 1.發送請求
import requests
import time
def get_page(url):
response = requests.get(url)
return response
# 2.解析數據
import re
def parse_index(html):
#findall匹配所有
# re.findall('正則匹配規則','匹配文本','匹配模式')
#re.S:對全部文本進行搜索匹配
detail_urls=re.findall('div class="items"><a class="imglink" href="(.*?)"', html, re.S)
return detail_urls
# 解析詳情頁
def parse_detail(html):
movie_url=re.findall('<source src="(.*?)"',html,re.S)
if movie_url:
return movie_url[0]
# 3.保存數據
import uuid
# uuid.uuid4()根據時間戳生成一段世界上唯一的字符串
def save_video(content):
with open(f'{uuid.uuid4()}.mp4','wb') as f:
f.write(content)
print('視頻下載完畢')
# main +回車鍵
# 測試用例:
if __name__ == '__main__':
for line in range(6):
url=f'http://www.xiaohuar.com/list-3-{line}.html'
# 發送請求
response=get_page(url)
# print(respone)
# # 返回響應狀態碼
# print(response.status_code)
# 返回響應文本
# print(response.text)
# 解析主頁頁面
detail_urls=parse_index(response.text)
# 循環遍歷詳情頁url
for detail_url in detail_urls:
# 往每一個詳情頁發送請求
detail_res = get_page(detail_url)
# 解析詳情頁獲取視頻url
movie_url = parse_detail(detail_res.text)
# 判斷url存在打印視頻
if movie_url:
print(movie_url)
# 往視頻url發送請求獲取視頻二進制流
movie_res = get_page(movie_url)
# 把視頻的二進制流給save_video函數去保存到本地
save_video(movie_res.content)