爬蟲基本流程 re正則表達(dá)式 (內(nèi)置模塊) requests >>> pip install requests 在CMD 命令符 win + R json數(shù)據(jù)解析方法 視頻數(shù)據(jù)保存
找數(shù)據(jù)對應(yīng)的地址 使用python代碼發(fā)送請求 數(shù)據(jù)篩選 數(shù)據(jù)保存
用selenium自動化框架爬取數(shù)據(jù)import requests # 數(shù)據(jù)請求 第三方模塊 pip install requestsimport re # 正則表達(dá)式模塊 內(nèi)置模塊from selenium import webdriver # 測試模擬 模擬人去操作瀏覽器 pip install seleniumimport pprint # 格式化輸出模塊import time # 時間模塊# 需要谷歌/火狐驅(qū)動 python的環(huán)境安裝在哪 就放那driver = webdriver.Chrome() # 把驅(qū)動直接放在python安裝的路徑里面 實(shí)例化一個瀏覽器對象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) # 隱式等待 等待數(shù)據(jù)加載 加載完成之后才繼續(xù)運(yùn)行后面的內(nèi)容
# time 延時有點(diǎn)區(qū)別 死等
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字典數(shù)據(jù) 可以直接根據(jù)鍵值對 提取數(shù)據(jù)內(nèi)容 冒號左邊 提取冒號右邊的
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 # 獲取二進(jìn)制數(shù)據(jù)內(nèi)容
# 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}頁數(shù)據(jù)內(nèi)容')
get_video_content()
driver.find_element_by_css_selector('.next').click()
time.sleep(1)
|