import requests # 數據請求 第三方模塊 pip install requests
import re # 正則表達式模塊 內置模塊
from selenium import webdriver # 測試模擬 模擬人去操作瀏覽器 pip install selenium
import pprint # 格式化輸出模塊
import time # 時間模塊
# 需要谷歌/火狐驅動 python的環境安裝在哪 就放那
driver = webdriver.Chrome() # 把驅動直接放在python安裝的路徑里面 實例化一個瀏覽器對象
driver.get('https://v.huya.com/g/all?set_id=31&order=hot&page=1')
def get_video_content():
# time.sleep(2)
driver.refresh()
driver.implicitly_wait(10) # 隱式等待 等待數據加載 加載完成之后才繼續運行后面的內容
# time 延時有點區別 死等
lis = driver.find_elements_by_css_selector('.vhy-video-list li')
for li in lis:
video_url = li.find_element_by_css_selector('.video-wrap').get_attribute('href')
print(video_url)
video_id = re.findall('https://v\.huya\.com/play/(.*?)\.html', video_url)[0]
headers = {
# 'Cookie': 'SoundValue=0.50; isInLiveRoom=; udb_guiddata=f88bdbcfecb444cbaebfd3430e0c220c; udb_deviceid=w_491619378696527872; udb_anouid=1462126356760; Hm_lvt_51700b6c722f5bb4cf39906a596ea41f=1631947193; __yasmid=0.5061768216828664; __yamid_tt1=0.5061768216828664; __yamid_new=C986054DD8700001912A6690BBA03A50; _yasids=__rootsid%3DC986054DD8900001E8251C028DB01560; Hm_lvt_9fb71726843792b1cba806176cecfe38=1631947194; udb_passdata=3; hiido_ui=0.8655862701494763; Hm_lpvt_51700b6c722f5bb4cf39906a596ea41f=1631948597; Hm_lpvt_9fb71726843792b1cba806176cecfe38=1631948597; rep_cnt=96',
# 'Host': 'v.huya.com',
# 'Pragma': 'no-cache',
# 'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',
}
index_url = f'https://liveapi.huya.com/moment/getMomentContent?videoId={video_id}&uid=&_=1631947292202'
json_data = requests.get(url=index_url, headers=headers).json()
# json字典數據 可以直接根據鍵值對 提取數據內容 冒號左邊 提取冒號右邊的
play_url = json_data['data']['moment']['videoInfo']['definitions'][0]['url']
title = json_data['data']['moment']['videoInfo']['videoTitle']
# video_content = requests.get(url=play_url, headers=headers).content # 獲取二進制數據內容
# with open('video\\' + title + '.mp4', mode='wb') as f:
# f.write(video_content)
print(title, play_url)
for page in range(1, 3):
print(f'正在爬取第{page}頁數據內容')
get_video_content()
driver.find_element_by_css_selector('.next').click()
time.sleep(1)