先來看看我們本次要爬的內容


本文主要知識點:
- 爬蟲基本流程
- re正則運算式 (內置模塊)
- requests >>> pip install requests 在CMD 命令符 win + R
- json資料決議方法
- 視頻資料保存
開發環境:
- Python 3.6 / 3.8
- Pycharm (專業需要激活碼 社區免費) 安裝包 安裝教程 使用教程 激活碼 翻譯插件
- 谷歌/火狐瀏覽器驅動
【付費VIP完整版】只要看了就能學會的教程,80集Python基礎入門視頻教學
爬蟲主要步驟:
- 找資料對應的地址
- 使用python代碼發送請求
- 資料篩選
- 資料保存
用selenium自動化框架爬取資料
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=https://www.cnblogs.com/qshhl/archive/2021/09/22/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)
運行代碼,得到結果

對于本篇文章有疑問的同學也可以點這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/302118.html
標籤:其他
