1. 程式人生 > 實用技巧 >Python爬取糗事百科視訊

Python爬取糗事百科視訊

一、題目要求:爬取糗事百科上的視訊並下載到本地磁碟

二、程式碼

import requests
import re

headers = headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'}#偽裝成瀏覽器正常訪問瀏覽器,建立頭部資訊
'''
url = 'https://www.qiushibaike.com/video/page/{}'#爬取多頁。
for i in range(1,4):
  print(url.format(i))
''' url = 'https://www.qiushibaike.com/video'#爬取單頁 resp = requests.get(url,headers=headers) #print( resp )得到一個響應狀態嗎。200表示成功然後418表示反爬 #print( resp.request.headers )這裡就是為神魔需要偽裝成瀏覽器 #print(resp.text)返回內容 info = re.findall(r'<source src="(.*)" type=\'video/mp4\' />',resp.text)#引數:查詢的規則,資料 #print(type(info))提取出來的資料是一個列表
lst=[] #用於儲存拼接後的url for item in info: lst.append('https:'+item) #print(lst)進行輸出檢視 '''接下來一個一個發請求''' count=0 for item in lst: #傳送請求 resp=requests.get(item,headers=headers) count+=1 #上下文管理(視訊儲存到哪裡)第一個引數為位置第二個引數為開啟方式,str的作用是型別轉換 with open('video/'+str(count)+'.mp4','wb') as file:
#寫入到本地磁碟 file.write(resp.content) #content說明的是二進位制的而text是文字 print("視訊下載完畢")
video.py

三、結果